Issue
I'm an Android newbie, trying to load some images using an async task and populate them into a ListView
. However with my current code, the images are not getting set to the correct ImageViews
and they change whenever I scroll. I can not find the mistake I am making. Thank you in advance.
public class BookAdapter extends ArrayAdapter<Book> {
public BookAdapter(Context context, ArrayList<Book> objects) {
super(context, 0, objects);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
View booksView = convertView;
// inflate a view if its empty
if (booksView == null) {
holder = new ViewHolder();
booksView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
holder.bookName = booksView.findViewById(R.id.book_name_textView);
holder.publishedDate = booksView.findViewById(R.id.dateTextView);
holder.bookAuthor = booksView.findViewById(R.id.author_textView);
holder.bookImage = booksView.findViewById(R.id.book_image);
booksView.setTag(holder);
} else {
holder = (ViewHolder) booksView.getTag();
}
Book currentBook = getItem(position);
if (holder.bookImage != null && currentBook.getBookImage()!=null) {
new LoadImages(holder.bookImage).execute(currentBook.getBookImage());
}
holder.bookName.setText(currentBook.getBookName());
holder.bookAuthor.setText(currentBook.getAuthor());
holder.publishedDate.setText(currentBook.getDate());
return booksView;
}
private class ViewHolder {
ImageView bookImage;
TextView bookName;
TextView bookAuthor;
TextView publishedDate;
}
}
Using the following class for asynctask
public class LoadImages extends AsyncTask<String,Void,Bitmap>{
private WeakReference<ImageView> imageview;
public LoadImages(ImageView imv){
imageview=new WeakReference<ImageView>(imv);
}
/** Background process
* input:url
* output: Bitmap image
* It passed into onPostExecute method
**/
@Override
protected Bitmap doInBackground(String... urls) {
return QueryUtils.fetchBookImages(urls[0]);
}
/** This method called after the doINputBackground method
* input:Bitmap image
* output: image set into the image view
* Image view passed from RecyclerViewOperation to ShowImage class through constructor
**/
@Override
protected void onPostExecute(Bitmap result) {
if((imageview!=null)&&(result!=null)){
ImageView imgview=imageview.get();
if(imgview!=null){
imgview.setImageBitmap(result);
}
}
}
}
Note: fetchBookImages class loads returns bitmap.
Solution
Please there are well known libraries that already solve the problem you are facing.
And so many others that you can find here.
Answered By - Maxime Claude
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.