I want to show images from the resource directory (all of them are saved in png format) in my ListView
, but it is extremely laggy. I am a complete noob so I need help with the asynchronous tasks to remove lags.
List Adapter:
public class MyListAdapter extends ArrayAdapter < SettingsItem > {
Context context;
List < SettingsItem > items;
public MyListAdapter(Context context, int resource, List < SettingsItem > objects) {
super(context, resource, objects);
this.context = context;
items = objects;
}
@Override
public View getView(int position, View itemView, ViewGroup parent) {
ViewHolder holder;
if (itemView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
itemView = inflater.inflate(R.layout.settings_items, parent, false);
holder = new ViewHolder();
holder.imageView = (ImageView) itemView.findViewById(R.id.item_icon);
holder.textView = (TextView) itemView.findViewById(R.id.item_text);
itemView.setTag(holder);
} else {
holder = (ViewHolder) itemView.getTag();
}
SettingsItem settingsItem = items.get(position);
if (settingsItem != null) {
holder.textView.setText(settingsItem.getName());
new ImageDownloaderTask(holder.imageView, getContext(), settingsItem.getIcon_id()).execute();
}
return itemView;
}
static class ViewHolder {
ImageView imageView;
TextView textView;
}
}
Row class:
public class SettingsItem{
private String name;
private int icon_id;
public SettingsItem(String a, int b){
super();
name=a;
icon_id=b;
}
public String getName() {
return name;
}
public int getIcon_id() {
return icon_id;
}
}
AsyncTask:
class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
Context context;
int id;
public ImageDownloaderTask(ImageView imageView, Context context, int id) {
imageViewReference = new WeakReference<ImageView>(imageView);
this.context=context;
this.id=id;
}
@Override
protected Bitmap doInBackground(String... params) {
return BitmapFactory.decodeResource(context.getResources(),id );
}
@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);
} else {
imageView.setImageResource(R.drawable.medical_bag);
}
}
}
}
}
I really need some help with this.
Thanks in advance. :)