Question

I am developing an application for android on which I have a listview displaying some Users. Thus I want to display their pictures inside this list view so I do as follow:

private class StableArrayAdapter extends ArrayAdapter<Request>{
    private Context context;
    private Bitmap tempobmp;
    private List<User> mylist;
    public StableArrayAdapter(Context context,List<User> mylist){
        super(context, R.layout.request_layout, mylist);
        this.context = context;
        this.mylist = mylist;
    }
    public class ViewHolder{
        public ImageView image;
      }
    public View getView(int position,View convertView,ViewGroup parent){
        View vi = convertView;
        if(vi==null){
            ViewHolder holder = new ViewHolder()
            holder.image = (ImageView) vi.findViewById(R.id.requestImage);
        }
        final ViewHolder holder = (ViewHolder) vi.getTag();
        User s = mylist.get(position);
        try{

            final URL url = new URL(myapp.getUser().getPhoto().getS3Url());
            Thread thread = new Thread(new Runnable() {
                  @Override
                  public void run() {
                      try{
                        InputStream is = (InputStream) url.getContent();

                        Bitmap bmp = BitmapFactory.decodeStream(is);

                        tempobmp=bmp;

                      }
                      catch(Exception e){
                          Log.d("eeeeA52","eeeeA52"+e);
                      }
                  }
            });
            thread.start(); 
            thread.wait();

        }
        catch(Exception e){
            Log.d("eeeeAF","eeeeAF"+e);
        }
        holder.image.setImageBitmap(tempobmp);
      return vi;
    }

All the logs I can put inside my thread tell me that it has no problems to get the bitmap from my database but when I launch the page with this ListView the image are still the default ones. Is it possible to use a thread in adapter in the way to retrieve network datas? If yes which is the best practice for it?

Thank you guys :)

Was it helpful?

Solution

Generally, it's considered a bad idea to make network calls directly from the Adapter. but If you are actually unable to perform your downloads in your activity/fragment prior to populating your listview, you can use one of the many libraries that do this like Volley that has a networkimageview object just for that. Or you can use the Picasso library that is build specifically for downloading images from the net and displaying in a regular imageView

Both are well documented and easy to use. (Picasso requires 1 line of code)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top