Access web images application

Asked

Viewed 302 times

5

I am beginner in android app development; I have the following question: if I want to make an application where the images used are not within the project, but on the web, what is the best way to make this connection. It would be worth accessing the URL class or using the Webservice?

3 answers

4

You can create a AsyncTask to load images asynchronously. See the codes below for how to do:

private class FetchImageTask extends AsyncTask<String, Integer, Bitmap> {
    @Override
    protected Bitmap doInBackground(String... arg0) {
        Bitmap b = null;
        try {
            b = BitmapFactory.decodeStream((InputStream) new URL(arg0[0]).getContent());
        }
        catch (MalformedURLException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return b;
    }
}

And to implement use this code:

new FetchImageTask() {
        @Override
        protected void onPostExecute(Bitmap result) {
            if (result != null) {
                image.setImageBitmap(result);
            }
        }
    }.execute("IMAGE_URL");

EDIT

Example on Github

  • But is that recommended? It’s a car accessory sales app. What would be better, like this or using the client/server connection?

  • What I would recommend you to do is to save the images to a server, be it Apache, IIS, Wildfly or any other server you prefer. Save the image path in Sqlite database on Android, for example, IP_SERVIDOR:8080/aplicacao/imagens_carros/corcel.jpg to view the image of the car Corcel, consulting in the Sqlite database that URL and passing the URL of the image where it is written IMAGE_URL of the example I gave you. Any doubt just call.

  • Thanks, Giancarlo... I’ll try that way!

  • Giancarlo, would you indicate some video of someone using this process?

  • Worst I don’t have, I can create a page and make a tutorial as soon as I have time, but it’s not hard to create. You download Apache and install it on the machine, create an application directory, and inside that directory the images folder where the pictures of the cars are. Ai on Android performs the URL path request of the image. Brought.

  • Giancarlo, I have done a lot of research but not solved these doubts: How to save images in Apache or Engix; How to save the path in the Sqlite database; What is the importance of JSON in this case? I’m sorry, but even though I’ve studied this subject a lot, I find it very fragmented. Deciding to use Fresco lib and Engix server, but not understanding the server access process.

  • I created a repository on Github and I will do the example showing how it works once I have time, this week. Ai edit my post with the example here (;

  • Right... Valew!

  • Friend, I changed the post, I put a link that leads to one of my directories on Github with a small example project I did using Android and an Apache server carrying an image of a lion. There are instructions on how to install and configure Apache that I believe was what you wanted, so you can build a cool web service for your project. You have a reference to help you with anything.

  • I couldn’t look before, but I’ll take a look and anything I ask for your help. Right? Thank you.

  • Can’t your project be downloaded for testing? I found it very difficult to understand from Github.

  • Yes, but you have to configure the development environment, I put there how to install, very easy.

  • I opened your project, but it didn’t work... your image doesn’t open.

  • It works because I tested it here before giving you the link.

Show 9 more comments

3

You can solve this only in one line using the image lib, it can be both the Picasso, Glide, Universal Image Loader.Example with Picasso:

Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

Explaining. first you pass the context of your Class, according to the Image Url and last your Imageview. It is very simple.
Link from the lib: http://square.github.io/picasso/

  • Thanks, Alessandro... I’ll study that option too.

  • Thanks, I didn’t know about Picasso.

  • But the fact that you use this lib doesn’t mean that you don’t need a server; that’s not it?

  • you can and have to use a server yes, because without the server your images will get static and already with the server you will have greater control, search on web service communication with android and JSON. Then you use the lib to get this information from the server that will be passed in a JSON and so play in the lib load.

  • Beauty, Alessandro!

1

When I need to access some web content with android I use the Volley library, it is very simple to use. Here is a link to an example that requests an image:

https://developer.android.com/training/volley/request.html#request-image

Edit- Example of use:

First you add the . library jar to your project. Then you can make the request very simple: just create an instance of Stringrequest (for text), in the constructor you can explain the method you need (POST or GET), then the URL (in my example the url is in Requestcontract.XMLQuestionarioContract.XML_QUESITIONARIO_URL) and last only need to implement the system, in onResponse the return will be in the method parameter. Last only need to add the request in a queue.

 private void requestQuestionario(){
    String tag_string_req = "req_questionario"; //tag para cancelar o request

    pDialog.setMessage("Carregando Questionário...");
    showDialog();

    StringRequest stringRequest = new StringRequest(Request.Method.GET,
            RequestContract.XMLQuestionarioContract.XML_QUESITIONARIO_URL, new Response.Listener<String>() {

        @Override
        public void onResponse(String s) {
            Log.d(TAG, "Response = " + s);

            //TODO -- Tratar Response
            InputStream xml = new ByteArrayInputStream(s.getBytes());
            try {
                HashMap questionario = XmlParser.parse(xml);
                List<Questao> questoes = (List) questionario.get("questoes");
                List<Alternativa> alternativas = (List) questionario.get("alternativas");
                List<Codigo> codigos = (List) questionario.get("codigos");

                DataBaseHelper db = new DataBaseHelper(getApplicationContext());

                db.insertQuestoes(questoes);
                db.insertAlternativas(alternativas);
                db.insertCodigos(codigos);

            } catch (XmlPullParserException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (SQLException e){
                e.printStackTrace();
            }

            hideDialog();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            //TODO -- Tratar erro
            Log.e(TAG, "Erro no request");
            hideDialog();
        }
    });

    requestQueue = RequestManager.getInstance(this).getRequestQueue();

    stringRequest.setTag(tag_string_req);
    requestQueue.add(stringRequest);
}

In this example I use the contents of onResponse’s String(String s) to make the Parsing of an XML, but it could be any String or even a Json.

For Requestqueue the Google Documentation recommends using a Singleton, but can be instantiated as follows:

RequestQueue queue = Volley.newRequestQueue(this);

To request an image in the google documentation use this example:

ImageView mImageView;
String url = "http://i.imgur.com/7spzG.png";
mImageView = (ImageView) findViewById(R.id.myImage);
...

// Retrieves an image specified by the URL, displays it in the UI.
ImageRequest request = new ImageRequest(url,
   new Response.Listener<Bitmap>() {
       @Override
       public void onResponse(Bitmap bitmap) {
           mImageView.setImageBitmap(bitmap);
       }
   }, 0, 0, null,
   new Response.ErrorListener() {
       public void onErrorResponse(VolleyError error) {
           mImageView.setImageResource(R.drawable.image_load_error);
       }
   });
  // Access the RequestQueue through your singleton class.
  MySingleton.getInstance(this).addToRequestQueue(request);

Stringrequest was replaced by an Imagerequest and onResponse parameter with a Bitmap

  • 1

    Can you give a brief summary of how you use this library? Without this your answer becomes very simple.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.