Show image in listview from url with Android Studio

1

public class MainActivity extends AppCompatActivity {
ListView lista;
ArrayList imagen=new ArrayList();
ArrayList posicion=new ArrayList();
ArrayList hora=new ArrayList();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lista=findViewById(R.id.lista);
        descargarImagen();
    }

    private void descargarImagen() {
        imagen.clear();
        posicion.clear();
        hora.clear();

        final ProgressDialog progressDialog=new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("Cargando datos...");
        progressDialog.show();

        AsyncHttpClient client= new AsyncHttpClient();
        client.get("http://192.168.2.19/android/control/jquery.php", new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode==200){
                    progressDialog.dismiss();
                    try {
                        JSONArray jsarray=new JSONArray(new String(responseBody));
                        for (int i=0;i<jsarray.length();i++){
                            imagen.add(jsarray.getJSONObject(i).getString("imagen"));
                            posicion.add(jsarray.getJSONObject(i).getString("posicion"));
                            hora.add(jsarray.getJSONObject(i).getString("hora"));


                        }
                        lista.setAdapter(new ImagenAdapter(getApplicationContext()));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });
    }
    private class ImagenAdapter extends BaseAdapter{

        Context ctx;
        LayoutInflater layoutInflater;
        ImageView img;
        TextView tposicion,thora;

        public ImagenAdapter(Context applicationContext) {
            this.ctx=applicationContext;
            layoutInflater= (LayoutInflater) ctx.getSystemService(LAYOUT_INFLATER_SERVICE);

        }

        @Override
        public int getCount() {
            return imagen.size();
        }

        @Override
        public Object getItem(int i) {
            return tposicion;
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewGroup viewGroup1=(ViewGroup)layoutInflater.inflate(R.layout.lista,null);
            img=(ImageView)viewGroup1.findViewById(R.id.img);
            tposicion=(TextView)viewGroup1.findViewById(R.id.txt1);
            thora=(TextView)viewGroup1.findViewById(R.id.txt2);

            String urlfinal="http://192.168.2.19/android/control/img/" + imagen.get(i).toString();
            Rect rect = new Rect(img.getLeft(),img.getTop(),img.getRight(),img.getBottom());

            img.setImageurl(urlfinal);
            tposicion.setText(posicion.get(i).toString());
            thora.setText(hora.get(i).toString());
            return viewGroup1;
        }
    }
}

I'm having problems because I think

  

img.setimageurl ();

Is any idea of how to do it obsolete?

    
asked by adrian ruiz picazo 09.03.2018 в 10:19
source

2 answers

1

Instead of putting together a church arch to download the image asynchronously, you could use an external library that already does everything for you, reducing the work to literally a single line. I recommend Picasso .

You must import the library in your gradle:

compile 'com.squareup.picasso:picasso:(insert latest version)'

Applying it to your code, the getview of the adapter should look something like this:

@Override 
public View getView(int i, View view, ViewGroup viewGroup) {
  ViewGroup viewGroup1 (ViewGroup)layoutInflater.inflate(R.layout.lista,null);
  img=(ImageView)viewGroup1.findViewById(R.id.img);
  tposicion=(TextView)viewGroup1.findViewById(R.id.txt1);
  thora=(TextView)viewGroup1.findViewById(R.id.txt2);

  String urlfinal="http://192.168.2.19/android/control/img/" + imagen.get(i).toString();
  Rect rect = new Rect(img.getLeft(),img.getTop(),img.getRight(),img.getBottom());

  Picasso.with(ctx).load(urlfinal).into(img); //con una línea te descarga asíncronamente la imagen y te la inserta en tu imageview. Awesome =)

  tposicion.setText(posicion.get(i).toString());
  thora.setText(hora.get(i).toString());
  return viewGroup1;
}
    
answered by 09.03.2018 / 12:09
source
2

Regarding the loading of the images from a url you can use several options, I add 3:

is usually done is to load the images from resources or from a url, the dependency is added within the file build.gradle :

repositories {
  mavenCentral()
  google()
}

dependencies {
  implementation 'com.github.bumptech.glide:glide:4.6.1'
  annotationProcessor 'com.github.bumptech.glide:compiler:4.6.1'
}

this is an example:

//Obtienes la referencia del ImageView en donde se cagaría la imagen.
ImageView imageView = (ImageView) findViewById(R.id.imageView);

//Indicas a Glide que imagen cargar y en que vista.
Glide.with(context)
    .load("http://www.midominio.com/myimagen.jpg")
    .into(imageView);

The interesting thing about Glide is that it manages the cache and memory required to process the image in an optimal way, in addition to that it is much easier to implement with respect to Universal Image Loader .

very similar to Glide, it also includes cache management. Add the dependency within the build.gradle file

compile 'com.squareup.picasso:picasso:2.71828'

and this is an example:

Picasso.
  with(context).
  load("http://www.midominio.com/myimagen.jpg").
  into(imageView);
  • AsynctTask

How to download image in an ImageView using AsynctTask.

You create an Asynctask where the download process is done within the doInBackground() method:

class LoadImage extends AsyncTask<String, Void, Bitmap> {

    private final WeakReference<ImageView> imageViewReference;

    public LoadImage(ImageView imageView) {
        imageViewReference = new WeakReference<ImageView>(imageView);
    }

    @Override
    protected Bitmap doInBackground(String... params) {
        try {
            return downloadBitmap(params[0]);
        } catch (Exception e) {
            Log.e("LoadImage class", "doInBackground() " + e.getMessage());
        }
        return null;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        if (isCancelled()) {
            bitmap = null;
        }

        if (imageViewReference != null) {
            ImageView imageView = imageViewReference.get();
            if (imageView != null) {
                if (bitmap != null) {
                    imageView.setImageBitmap(bitmap);
                }
            }
        }
    }

    private Bitmap downloadBitmap(String url) {
        HttpURLConnection urlConnection = null;
        try {
            URL uri = new URL(url);
            urlConnection = (HttpURLConnection) uri.openConnection();
            int statusCode = urlConnection.getResponseCode();
            if (statusCode != HttpURLConnection.HTTP_OK) {
                return null;
            }

            InputStream inputStream = urlConnection.getInputStream();
            if (inputStream != null) {
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                return bitmap;
            }
        } catch (Exception e) {
            urlConnection.disconnect();
            Log.e("LoadImage class", "Descargando imagen desde url: " + url);
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
        return null;
    }
}

and you would call in this way the AsyncTask to load the downloaded image, defining the container ImageView and the url of the image to download:

   private ImageView imageView;
   private String imageHttpAddress = "http://jonsegador.com/wp-content/apezz.png";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = (ImageView) findViewById(R.id.image_view);
        //downloadFile(imageHttpAddress);
        //AsyncTask recibe la referencia del ImageView y la url a descargar.
        new LoadImage(imageView).execute(imageHttpAddress);
    }

to get:

answered by 09.03.2018 в 14:41