serkan stack serkan stack - 1 month ago 17
Android Question

setImage ImageAdapter Android

I downloaded JSON data and converted into POJO Objects successfully. Now, I have a problem that "How can I set image from URL to imagivew attribute of view holder?"

ImagesAdapter.java:

package gc.x;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import gc.ovidos_challenge.R;
import gc.ovidos_challenge.models.Image;

import java.net.URL;
import java.util.List;


public class ImagesAdapter extends RecyclerView.Adapter<ImagesAdapter.MyViewHolder> {

private List<Image> imagesList;

public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public ImageView imageview;

public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.textview);
imageview = (ImageView) view.findViewById(R.id.imageurl);

}
}


public ImagesAdapter(List<Image> imagesList) {
this.imagesList = imagesList;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_image, parent, false);

return new MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Image image = imagesList.get(position);
holder.title.setText(image.title);

// holder.imageview.setImage(image.url); //Problem is here, How can I implement?


}

@Override
public int getItemCount() {
return imagesList.size();
}


}


I couldn't imagine how to implement setImage method.

Image Class:

public class Image {

public String albumId;
public String id;
public String title;
public String url;
public String thumbnailUrl;

}

Answer

Without using External Library

    new DownloadImageTask(imageview).execute(url);

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> 
    {
        ImageView bmImage;

        public DownloadImageTask(ImageView bmImage) {
            this.bmImage = bmImage;
        }

        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }

        protected void onPostExecute(Bitmap result) {
            bmImage.setImageBitmap(result);
        }
    }

Using Library :

Picasso.with(context).load(image.url).into(//your_image_view );

and compile compile 'com.squareup.picasso:picasso:2.5.2'

or

Universal Image Loader Lib. Lite Weight.Fast and Easy to use. See this Link