Application access web images

5

I am a beginner in android application development; I have the following doubt: if I want to make an application in which the images used are not contained within the project, but on the web, what is the best way to make this connection. Is it possible to access via the URL class or using WebService?

    
asked by anonymous 16.09.2015 / 20:49

3 answers

4

You can create AsyncTask to load images asynchronously. Here are the codes below how to do it:

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

GitHub Example

    
16.09.2015 / 20:53
3

You can solve this only in one line using the image lib, it can be either 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 Image Url and finally your ImageView. It's very simple. Home Link from lib: link

    
17.09.2015 / 15:31
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 requesting an image:

link

Edit - Usage example:

First you add the .jar library to your project. Then you can perform the request very simply: just create an instance of StringRequest (for text), in the counter 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 lastly only need to implement the listener, in onResponse the return will be in the method parameter. Finally you just 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 the onResponse's String (s) to parse an XML, but it could be any String or even a Json.

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

RequestQueue queue = Volley.newRequestQueue(this);

To request an image in 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);

The StringRequest has been replaced by an ImageRequest and the onResponse parameter by a BitMap

    
21.09.2015 / 01:42