Android: LruCache issue with Bitmap - android

I have a global bitmap cache using LruCache class. when loading thumbnails for the listview, the cache is used first. It works just OK.
But one issue is: sometimes the Bitmap instance from the cache cannot be displayed on the listview. it seems such bitmap from cache is not valid any more. I have checked the bitmap from cache if it is not null and if it is not recycled, but it still seems such bitmap cannot be displayed (even it is not null and it is not recycled).
The cache class:
public class ImageCache {
private LruCache<String, Bitmap> mMemoryCache;
private static ImageCache instance;
public static ImageCache getInstance() {
if(instance != null) {
return instance;
}
instance = new ImageCache();
instance.initializeCache();
return instance;
}
protected void initializeCache() {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// Use 1/8th of the available memory for this memory cache.
final int cacheSize = maxMemory / 8;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
#Override
protected int sizeOf(String key, Bitmap bitmap) {
// The cache size will be measured in kilobytes rather than
// number of items.
return bitmap.getByteCount() / 1024;
}
};
}
public Bitmap getImage(String url) {
return this.mMemoryCache.get(url);
}
public void cacheImage(String url, Bitmap image) {
this.mMemoryCache.put(url, image);
}
}
and the code to use the cache is in the Adapter class which is subclass of CursorAdapter:
final ImageCache cache = ImageCache.getInstance();
// First get from memory cache
final Bitmap bitmap = cache.getImage(thumbnailUrl);
if (bitmap != null && !bitmap.isRecycled()) {
Log.d(TAG, "The bitmap is valid");
viewHolder.imageView.setImageBitmap(bitmap);
}
else {
Log.d(TAG, "The bitmap is invalid, reload it.");
viewHolder.imageView.setImageResource(R.drawable.thumbnail_small);
// use the AsyncTask to download the image and set in cache
new DownloadImageTask(context, viewHolder.imageView, thumbnailUrl, dir, filepath).execute();
}
the code of DownloadImageTask:
public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
private ImageView mImageView;
private String url;
private String dir;
private String filename;
private Context context;
public DownloadImageTask(Context context, ImageView imageView, String url, String dir, String filename) {
this.mImageView = imageView;
this.url = url;
this.filename = filename;
this.dir = dir;
this.context = context;
this.cache = cache;
}
protected Bitmap doInBackground(String... urls) {
// String urldisplay = urls[0];
final Bitmap bitmap = FileUtils.readImage(context, dir, filename, url);
return bitmap;
}
protected void onPostExecute(Bitmap result) {
final ImageCache cache = ImageCache.getInstance();
if(result != null) {
cache.put(url, result);
mImageView.setImageBitmap(result);
}
}
}
any help will be appreciated. Thanks!
Updates: I have followed the link suggested by greywolf82: section "Handle Configuration Changes". I put the following attribute in my activity class and the two fragment classes:
public LruCache mMemoryCache;
In the activity class, I try to initialize the cache when calling the fragment:
// Get the cache
mMemoryCache = mIndexFragment.mRetainedCache;
if (mMemoryCache == null) {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// Use 1/8th of the available memory for this memory cache.
final int cacheSize = maxMemory / 8;
// Initialize the cache
mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
#Override
protected int sizeOf(String key, Bitmap bitmap) {
// The cache size will be measured in kilobytes rather than
// number of items.
return bitmap.getByteCount() / 1024;
}
};
Log.d(TAG, "Initialized the memory cache");
mIndexFragment.mRetainedCache = mMemoryCache;
}
in the fragment class:
setRetainInstance(true);
and I pass the cache instance to the adapter constructor so that the adapter can use the cache.
but I still got the same issue.
Update 2:
the two adapter classes with changes to accept the LruCache instance:
NewsCursorAdapter:
public class NewsCursorAdapter extends CursorAdapter {
private static final String TAG = "NewsCursorAdapter";
private LruCache<String, Bitmap> cache;
private Context mContext;
public NewsCursorAdapter(Context context, LruCache<String, Bitmap> cache) {
super(context, null, false);
this.mContext = context;
this.cache = cache;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
final Setting setting = ApplicationContext.getSetting();
// Get the view holder
ViewHolder viewHolder = (ViewHolder) view.getTag();
final String thumbnail = cursor.getString(NewsContract.Entry.THUMBNAIL_CURSOR_INDEX);
if(thumbnail != null) {
String pictureDate = cursor.getString(NewsContract.Entry.PIC_DATE_CURSOR_INDEX);
final String dir = "thumbnails/" + pictureDate + "/";
final String filepath = thumbnail + "-small.jpg";
final String thumbnailUrl = setting.getCdnUrl() + dir + filepath;
//final ImageCache cache = ImageCache.getInstance();
// First get from memory cache
final Bitmap bitmap = cache.get(thumbnailUrl);
if (bitmap != null && !bitmap.isRecycled()) {
Log.d(TAG, "The bitmap is valid: " + bitmap.getWidth());
viewHolder.imageView.setImageBitmap(bitmap);
}
else {
Log.d(TAG, "The bitmap is invalid, reload it.");
viewHolder.imageView.setImageResource(R.drawable.thumbnail_small);
new DownloadImageTask(viewHolder.imageView, thumbnailUrl, dir, filepath).execute();
}
}
else {
viewHolder.imageView.setVisibility(View.GONE);
}
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.listview_item_row, parent,
false);
// Initialize the view holder
ViewHolder viewHolder = new ViewHolder();
viewHolder.titleView = (TextView) view.findViewById(R.id.title);
viewHolder.timeView = (TextView) view.findViewById(R.id.news_time);
viewHolder.propsView = (TextView) view.findViewById(R.id.properties);
viewHolder.imageView = (ImageView) view.findViewById(R.id.icon);
view.setTag(viewHolder);
return view;
}
static class ViewHolder {
TextView titleView;
TextView timeView;
TextView propsView;
ImageView imageView;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
private ImageView mImageView;
private String url;
private String dir;
private String filename;
public DownloadImageTask(ImageView imageView, String url, String dir, String filename) {
this.mImageView = imageView;
this.url = url;
this.filename = filename;
this.dir = dir;
}
protected Bitmap doInBackground(String... urls) {
final Bitmap bitmap = FileUtils.readImage(mContext, dir, filename, url);
return bitmap;
}
protected void onPostExecute(Bitmap result) {
//final ImageCache cache = ImageCache.getInstance();
if(result != null) {
cache.put(url, result);
mImageView.setImageBitmap(result);
}
}
}
}
the list adapter, NewsTopicItemAdapter:
public class NewsTopicItemAdapter extends ArrayAdapter<NewsTopicItem> {
private Context context = null;
private EntryViewHolder viewHolder;
private HeaderViewHolder headerViewHolder;
private LruCache<String, Bitmap> mCache;
public NewsTopicItemAdapter(Context context, List<NewsTopicItem> arrayList, LruCache<String, Bitmap> cache) {
super(context, 0, arrayList);
this.context = context;
this.mCache = cache;
}
public void setItems(List<NewsTopicItem> items) {
this.addAll(items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final NewsTopicItem item = getItem(position);
View view;
if(!item.isHeader()) {
view = this.getEntryView((NewsTopicEntry)item, convertView, parent);
}
else {
view = this.getHeaderView((NewsTopicHeader)item, convertView, parent);
}
return view;
}
protected View getEntryView(NewsTopicEntry newsItem, View convertView, ViewGroup parent) {
View view;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
viewHolder = new EntryViewHolder();
view = inflater.inflate(R.layout.listview_item_row, parent,
false);
// Initialize the view holder
viewHolder.titleView = (TextView) view.findViewById(R.id.title);
viewHolder.timeView = (TextView) view.findViewById(R.id.news_time);
viewHolder.propsView = (TextView) view.findViewById(R.id.properties);
viewHolder.imageView = (ImageView) view.findViewById(R.id.icon);
view.setTag(viewHolder);
viewHolder.propsView.setText(newsItem.getSource());
if (newsItem.getThumbnail() != null) {
final String dir = "thumbnails/" + newsItem.getPictureDate() + "/";
final String filepath = newsItem.getThumbnail() + "-small.jpg";
final String thumbnailUrl = "http://www.oneplusnews.com/static/" + dir + filepath;
//final ImageCache cache = ImageCache.getInstance();
// First get from memory cache
final Bitmap bitmap = mCache.get(thumbnailUrl);
if (bitmap != null && !bitmap.isRecycled()) {
viewHolder.imageView.setImageBitmap(bitmap);
} else {
viewHolder.imageView.setImageResource(R.drawable.thumbnail_small);
new DownloadImageTask(viewHolder.imageView, thumbnailUrl, dir, filepath).execute();
}
}
else {
viewHolder.imageView.setVisibility(View.GONE);
}
viewHolder.titleView.setText(newsItem.getTitle());
viewHolder.timeView.setText(DateUtils.getDisplayDate(newsItem.getCreated()));
return view;
}
protected View getHeaderView(NewsTopicHeader header, View convertView, ViewGroup parent) {
View view;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
headerViewHolder = new HeaderViewHolder();
view = inflater.inflate(R.layout.news_list_header, parent,
false);
// Initialize the view holder
headerViewHolder.topicView = (TextView) view.findViewById(R.id.topic);
view.setTag(headerViewHolder);
final View imageView = view.findViewById(R.id.more_icon);
imageView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Start the Fragement
}
});
Topic topic = header.getTopic();
if(topic.isKeyword()) {
headerViewHolder.topicView.setText(topic.getName());
}
else {
// This is a hack to avoid error with - in android
headerViewHolder.topicView.setText(ResourceUtils.getStringByName(context, topic.getName()));
}
return view;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
private ImageView mImageView;
private String url;
private String dir;
private String filename;
public DownloadImageTask(ImageView imageView, String url, String dir, String filename) {
this.mImageView = imageView;
this.url = url;
this.filename = filename;
this.dir = dir;
}
protected Bitmap doInBackground(String... urls) {
final Bitmap mIcon11 = FileUtils.readImage(context, dir, filename, url);
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
//final ImageCache cache = ImageCache.getInstance();
if(result != null) {
mCache.put(url, result);
mImageView.setImageBitmap(result);
}
}
}
static class EntryViewHolder {
TextView titleView;
TextView timeView;
TextView propsView;
ImageView imageView;
TextView topicView;
}
static class HeaderViewHolder {
TextView topicView;
}
}
Update 3: I have attached the debug information from eclipse: the 1st picture is the working bitmap, and the 2nd one is the non-working bitmap from cache. I didn't find anything suspicious.
The debug information of the working bitmap from the cache:
The debug information of the non-working bitmap from the cache:

Finally I figured out the problem. It is becuase of the adapter. in the adapter I have set some ImageView as invisible if no thumbnail is needed. when the user scrolls the list view, such ImageView instance will be reused, but the visibility is not updated.
so the cache itself is OK now. The solution is to check the visibility of the ImageView and update it if needed.
Anyway thanks a lot to greywolf82 for your time and the tip about the singleton pattern.

The singleton pattern is the evil :) Please avoid it completely and use a fragment with setReteainInstance(true) as explained here

Related

Smooth scroll on listview with calllogs

I have a custom adapter added to listview. Data is call logs from phone. I reduce list by show only records from 3 days. Problem is that when I try to scroll listview from top to bottom I have a huge lags. My Scroll isn't smooth. Is there any way to make listview scroll smoother?
Here is my custom adapter:
public class CallListAdapter extends ArrayAdapter<CallList> {
Activity activity;
public CallListAdapter(Context context, ArrayList<CallList> calls, Activity activity) {
super(context, 0, calls);
this.activity = activity;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final CallList callList = getItem(position);
int actualPosition = 0;
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.call_list, parent, false);
}
final TextView call1 = convertView.findViewById(R.id.callNumber);
final TextView call2 = convertView.findViewById(R.id.callDate);
final TextView call3 = convertView.findViewById(R.id.conversationTime);
final TextView call4 = convertView.findViewById(R.id.callType);
final Button callView = convertView.findViewById(R.id.getViewName);
final ImageView bio = convertView.findViewById(R.id.lookBio);
final ImageView edit = convertView.findViewById(R.id.edit_call);
final ImageView block = convertView.findViewById(R.id.blockCall);
final ImageView call = convertView.findViewById(R.id.callUser);
final TextView bioLabel = convertView.findViewById(R.id.BioLabelSug);
final TextView editLabel = convertView.findViewById(R.id.NoteLabel);
final TextView blockLabel = convertView.findViewById(R.id.BlockLabelSug);
final TextView callLabel = convertView.findViewById(R.id.CallLabelSug);
final ConstraintLayout callContainer = convertView.findViewById(R.id.contact_container);
final ConstraintLayout bioContainer = convertView.findViewById(R.id.bio_container);
final ConstraintLayout blockContainer = convertView.findViewById(R.id.ignore_container);
final ConstraintLayout noteContainer = convertView.findViewById(R.id.note_container);
final TextView btnMarg = convertView.findViewById(R.id.buttonMargin);
final TextView callListNr2 = convertView.findViewById(R.id.callNumber2);
final LayoutInflater factory = activity.getLayoutInflater();
final View fullView = factory.inflate(R.layout.fragment_calls, null);
final RelativeLayout loading = fullView.findViewById(R.id.loadingBar);
String[] jsonData = new manageCalls().intentCallValues(position);
StringBuilder builder = new StringBuilder();
for (String s : jsonData) {
builder.append(s + "\n");
}
String str = builder.toString();
final String num = jsonData[0];
final String dat = jsonData[1];
final String typeCall = jsonData[2];
final String dur = jsonData[3];
final String authToken = SaveSharedPreferences.getPrefTokenName(getContext());
final Animation slideUp = AnimationUtils.loadAnimation(getContext(), R.anim.slideup);
final Animation slideDown = AnimationUtils.loadAnimation(getContext(), R.anim.slidedown);
final Handler handler = new Handler();
callView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (bioContainer.getVisibility() == View.GONE) {
callListNr2.setVisibility(View.GONE);
bio.setVisibility(View.VISIBLE);
bioLabel.setVisibility(View.VISIBLE);
edit.setVisibility(View.VISIBLE);
editLabel.setVisibility(View.VISIBLE);
} else if (bioContainer.getVisibility() == View.VISIBLE) {
handler.postDelayed(new Runnable() {
#Override
public void run() {
bio.setVisibility(View.GONE);
callContainer.setVisibility(View.GONE);
bioContainer.setVisibility(View.GONE);
noteContainer.setVisibility(View.GONE);
blockContainer.setVisibility(View.GONE);
}
}, 300);
}
}
});
if (actualPosition != position) {
if (bioContainer.getVisibility() == View.VISIBLE) {
bioContainer.setVisibility(View.GONE);
callContainer.setVisibility(View.GONE);
noteContainer.setVisibility(View.GONE);
blockContainer.setVisibility(View.GONE);
}
actualPosition = position;
}
call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
call.setEnabled(false);
loading.setVisibility(View.VISIBLE);
Intent intentCall = new Intent(view.getContext(), CallUserActivity.class);
intentCall.putExtra("number", num);
intentCall.putExtra("authToken", authToken);
intentCall.putExtra("Date", dat);
activity.startActivityForResult(intentCall, position);
handler.postDelayed(new Runnable() {
#Override
public void run() {
call.setEnabled(true);
loading.setVisibility(View.GONE);
}
}, 1000);
}
});
call2.setText(callList.callDate);
call3.setText(callList.conversationTime);
call4.setText(callList.callType);
return convertView;
}
}
Try use ViewHolder and use AsyncTask to load bitmap.
You can try this way.
private static class ViewHolder {
public TextView call1;
public TextView call2;
public TextView call3;
public TextView call4;
public Button callView;
public ImageView bio;
public ImageView edit;
public ImageView block;
public ImageView call;
public TextView bioLabel;
public TextView editLabel;
public TextView blockLabel;
public TextView callLabel;
public ConstraintLayout callContainer;
public ConstraintLayout bioContainer;
public ConstraintLayout blockContainer;
public ConstraintLayout noteContainer;
public TextView btnMarg;
public TextView callListNr2;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
// inflate the layout
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.call1 = convertView.findViewById(R.id....);
holder.call2 = convertView.findViewById(R.id....);
//Same for all other views
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.call1.setText(....);
//Lazy load for bitmap
loadBitmap(yourFileName..., bio)
return convertView;
}
static class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
BitmapWorkerTask(ImageView imageView) {
// Use a WeakReference to ensure the ImageView can be garbage collected
imageViewReference = new WeakReference<ImageView>(imageView);
}
// Decode image in background.
#Override
protected Bitmap doInBackground(String... params) {
return decodeSampledBitmapFromResource(params[0], 300, 300);
}
// Once complete, see if ImageView is still around and set bitmap.
#Override
protected void onPostExecute(Bitmap bitmap) {
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
}
public void loadBitmap(String fileName, ImageView imageView) {
BitmapWorkerTask task = new BitmapWorkerTask(imageView);
task.execute(fileName);
}
public static Bitmap decodeSampledBitmapFromResource(String fileName,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(fileName, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(fileName, options);
}
Your getview is HUGE.
Your (if convertview==null) has basically almost no effect as you're setting up the view again anyways.
What you need to do is refactor the getview to not be so slow. one thing you can do is create a class that has all the findviews done already for you and put that then in the .tag of the converted view. change your onclicks to use that as well, in a manner where you don't have to recreate them(other ways to do that exist as well).
ideally your code for if you have a converted view already should be just the .settexts().
depending on the size of your list, you could just get away with creating a view for each callist and avoid recycling the converted views alltogether, in such case you could just create them in advance.
also depending on the size of your list you could just get away with creating a just a simple linearlayout instead inside a scrollview. if your list isn't huge and it's not for some old phones, it works just fine as well (Don't knock on this as bad advice until you try on your phone how huge it can be before a listview starts making more sense).

Using AsyncTask to load image files from internal storage

I am attempting to load picture files in the form of thumbnails from my internal storage to a list view. Currently, I am using a ViewHolder, but the loading is still choppy when scrolling so I am going to try to use an AsyncTask. However I can't get my head around how to structure the AsyncTask as most of the examples I've found deal with downloading from a website. I'm not even sure if I should subclass it in my BaseAdapter or in my MainActivity. I have added my baseadapter below with the unfinished AsyncTask at the bottom. How do I structure this to either: use the AsyncTask to assist the ViewHolder, or directly pass an image to AsyncTask and have it return the bitmap so the ListView will scroll smoothly?
public class ListViewAdapter extends BaseAdapter {
private static final int WIDTH = 250;
private static final int HEIGHT = 250;
private static final int ROTATION = 90;
private final static String TAG = "Pictures";
private final ArrayList<SelfieObject> mItems = new ArrayList<SelfieObject>();
private Context mContext;
private File mStorageDir;
private String mFilePrefix;
public ListViewAdapter(Context context, File storageDir, String filePrefix) {
mContext = context;
mStorageDir = storageDir;
mFilePrefix = filePrefix;
//get file list from storage to display
InitializeItemsFromStorage(storageDir, filePrefix);
}
//this method creates an array of files stored on the device or SD card.
private void InitializeItemsFromStorage(File storageDir, String prefix) {
log("in InitializeItemsFromStorage()");
mItems.clear();
File[] files = getFiles(storageDir, prefix);
for (File f : files) {
SelfieObject selfie = new SelfieObject(f);
mItems.add(selfie);
}
}
public void Update() {
log("in Update()");
InitializeItemsFromStorage(mStorageDir, mFilePrefix);
notifyDataSetChanged();
}
/*
* return the list of file objects of the given directory that begin with
* the prefix.
*/
private File[] getFiles(File storageDir, final String prefix) {
FileFilter fileFilter = new FileFilter() {
#Override
public boolean accept(File pathname) {
if (pathname.isFile() && pathname.getName().startsWith(prefix))
return true;
else
return false;
}
};
File[] result = storageDir.listFiles(fileFilter);
return result;
}
public int getCount() {
log("in getCount()");
return mItems.size();
}
public Object getItem(int position) {
log("in getItem()");
return mItems.get(position);
}
public long getItemId(int position) {
log("in getItemId()");
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.v(TAG, "in getView for position " + position +
", convertView is " +
((convertView == null)?"null":"being recycled"));
View newView = convertView;
ViewHolder holder;
if (null == convertView) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
newView = inflater.inflate(R.layout.single_item, null);
holder = new ViewHolder();
holder.description = (TextView) newView.findViewById(R.id.textView1);
holder.picture = (ImageView) newView.findViewById(R.id.imageView1);
newView.setTag(holder);
} else {
holder = (ViewHolder) newView.getTag();
}
holder.picture.setScaleType(ImageView.ScaleType.CENTER_CROP);
SelfieObject selfie = (SelfieObject) getItem(position);
setPic(holder.picture, new Point(WIDTH, HEIGHT), selfie.getPath());
TextView textView = (TextView) holder.description;
textView.setText(selfie.getName());
log("Exiting getView");
return newView;
}
static class ViewHolder {
ImageView picture;
TextView description;
}
public void add(SelfieObject listItem) {
mItems.add(listItem);
notifyDataSetChanged();
}
public ArrayList<SelfieObject> getList(){
return mItems;
}
public void removeAllViews(){
mItems.clear();
this.notifyDataSetChanged();
}
public static void setPic(ImageView imageView, Point requestedSize,
String pathName) {
// set the dimensions of the View
int targetW = requestedSize.x;
int targetH = requestedSize.y;
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(pathName, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(pathName, bmOptions);
imageView.setImageBitmap(bitmap);
imageView.setRotation(ROTATION);
}
//Automation logging tool
public void log(String s){
Log.i(TAG, s);
}
private class AsyncTaskLoadImage extends AsyncTask<Object, Void, Bitmap>{
private ImageView image;
private String path;
public AsyncTaskLoadImage(ImageView image){
this.image = image;
this.path = image.getTag().toString();
}
#Override
protected Bitmap doInBackground(Object... params) {
Bitmap bitmap = null;
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + path);
if(file.exists()){
bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
}
return bitmap;
}
}
}
The AsyncTask should do whatever is too slow to do in the UI thread. In this example, fetching and downsampling the image, and setting up the ViewHolder should be done in the background.
However, I suggest you do not try and fix the ListView by yourself, but rather have a look at already existing solutions, like: https://github.com/lucasr/smoothie
Also, I highly suggest you downsample your bitmaps, otherwise they will consume a lot of excess computing time and memory. While the previous can lag your UI when scrolling, the latter will get you a nice OutOfMemoryException. See: http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html

Images are repeating in ListView

I have implemented android app which should download images from server and display them in ListView, but very interesting thing occures while images are downloading
As you can see in video pictures which haven't been downloaded yet are represented by those which have been already downloaded. How that can happen? I've thinking about it almost two days.
http://www.youtube.com/watch?v=lxY-HAuJO0o&feature=youtu.be
here is my code of ListView adapter.
public class MoviesAdapter extends ArrayAdapter<ParkCinema> {
private ArrayList<ParkCinema> movieDataItems;
private Activity context;
public MoviesAdapter(Activity context, int textViewResourceId, ArrayList<ParkCinema> movieDataItems) {
super(context, textViewResourceId, movieDataItems);
this.context = context;
this.movieDataItems = movieDataItems;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.movie_data_row, null);
}
ParkCinema movie = movieDataItems.get(position);
if (movie!=null){
ImageView imageView = (ImageView) convertView.findViewById(R.id.movie_thumb_icon);
String url = movie.poster();
if (url!=null) {
Bitmap bitmap = fetchBitmapFromCache(url);
if (bitmap==null) {
new BitmapDownloaderTask(imageView).execute(url);
}
else {
imageView.setImageBitmap(bitmap);
}
}
}
return convertView;
}
private LinkedHashMap<String, Bitmap> bitmapCache = new LinkedHashMap<String, Bitmap>();
private void addBitmapToCache(String url, Bitmap bitmap) {
if (bitmap != null) {
synchronized (bitmapCache) {
bitmapCache.put(url, bitmap);
}
}
}
private Bitmap fetchBitmapFromCache(String url) {
synchronized (bitmapCache) {
final Bitmap bitmap = bitmapCache.get(url);
if (bitmap != null) {
return bitmap;
}
}
return null;
}
private class BitmapDownloaderTask extends AsyncTask<String, Void, Bitmap> {
private String url;
private final WeakReference<ImageView> imageViewReference;
public BitmapDownloaderTask(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
protected Bitmap doInBackground (String... source) {
url = source[0];
Bitmap image;
try{
image = BitmapFactory.decodeStream(new URL(url).openConnection().getInputStream());
return image;
}
catch(Exception e){Log.e("Error", e.getMessage()); e.printStackTrace();}
return null;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
addBitmapToCache(url, bitmap);
imageViewReference.get().setImageBitmap(bitmap);
}
}
}
Edit 3:
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.movie_data_row, null);
}
ParkCinema movie = movieDataItems.get(position);
ImageView imageView = (ImageView) convertView.findViewById(R.id.movie_thumb_icon);
if (movie!=null){
String url = movie.poster();
if (url != null) {
Bitmap bitmap = fetchBitmapFromCache(url);
if (bitmap == null) {
imageView.setImageResource(R.drawable.no_image);
new BitmapDownloaderTask(imageView).execute(url);
}
else {
imageView.setImageBitmap(bitmap);
}
}
else {
imageView.setImageResource(R.drawable.no_image);
}
}
else {
imageView.setImageResource(R.drawable.no_image);
}
return convertView;
}
Aha! I think I may know the issue. Right now, your getView method sets your ImageView like this:
Gets movie object at position
Pulls out the movie's thumbnail url
Using that url, it tries to find the image in the cache
If it finds the image, it sets it
If it can't find the image, it starts an async network request to go get it, and sets it after it gets downloaded.
Your issus arises since ListView reuses its rows' Views. When the first View scrolls off the screen, rather than inflate a new one, ListView passes the now offscreen row's View in as convertView for you to reuse (this is for efficiency).
When your getView gets a convertView that is getting reused, its ImageView has already been set from the row that had it before, so you see the old image from the offscreen row's View. With your current getView process, you check for the new row's image, and it doesn't find it in the cache, it starts a request to download it. While it is downloading, you see the old image until you get the new image.
To fix this, you need to make sure you set every field in the row's View immediately, to make sure you don't have any Views showing stale data. I would suggest you set the ImageView to the default drawable resource (you have set in your R.layout.movie_data_row) while you wait for the network download to get the image.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.movie_data_row, null);
}
ParkCinema movie = movieDataItems.get(position);
ImageView imageView = (ImageView) convertView.findViewById(R.id.movie_thumb_icon);
if (movie != null) {
String url = movie.poster();
if (url != null) {
Bitmap bitmap = fetchBitmapFromCache(url);
if (bitmap == null) {
// Set the movie thumbnail to the default icon while we load
// the real image
imageView.setImageResource(R.drawable.movie_thumb_icon);
new BitmapDownloaderTask(imageView).execute(url);
}
else {
// Set the image to the bitmap we get from the cache
imageView.setImageBitmap(bitmap);
}
}
else {
// Set the movie thumbnail to the default icon, since it doesn't
// have a thumbnail URL
imageView.setImageResource(R.drawable.movie_thumb_icon);
}
}
else {
// Set the movie thumbnail to the default icon, since there's no
// movie data for this row
imageView.setImageResource(R.drawable.movie_thumb_icon);
}
-Edit-
Updated to be even more robust, using your drawable. You also have an issue with your BitmapDownloaderTask, it does not handle errors/null. Try adding this as well.
#Override
protected void onPostExecute(Bitmap bitmap) {
addBitmapToCache(url, bitmap);
if (bitmap == null) {
// Set the movie thumbnail to the default icon, since an error occurred while downloading
imageViewReference.get().setImageResource(R.drawable.movie_thumb_icon);
}
else {
imageViewReference.get().setImageBitmap(bitmap);
}
}
i had this issue and implemented lruCache ...i believe you need api 12 and above or use the compatiblity v4 library. lurCache is fast memory but it also has a budget, so if your worried about that you can use a diskcache ...its all described here http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html
I'll now provide my implementation which is a singleton i call from anywhere like this:
//where first is a string and other is a imageview to load
DownloadImageTask.getInstance().loadBitmap(avatarURL, iv_avatar);
here's the ideal code to cache and then call the above in getView of an adapter when retrieving the web image:
public class DownloadImageTask {
private LruCache<String, Bitmap> mMemoryCache;
/* create a singleton class to call this from multiple classes */
private static DownloadImageTask instance = null;
public static DownloadImageTask getInstance() {
if (instance == null) {
instance = new DownloadImageTask();
}
return instance;
}
//lock the constructor from public instances
private DownloadImageTask() {
// Get max available VM memory, exceeding this amount will throw an
// OutOfMemory exception. Stored in kilobytes as LruCache takes an
// int in its constructor.
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// Use 1/8th of the available memory for this memory cache.
final int cacheSize = maxMemory / 8;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
#Override
protected int sizeOf(String key, Bitmap bitmap) {
// The cache size will be measured in kilobytes rather than
// number of items.
return bitmap.getByteCount() / 1024;
}
};
}
public void loadBitmap(String avatarURL, ImageView imageView) {
final String imageKey = String.valueOf(avatarURL);
final Bitmap bitmap = getBitmapFromMemCache(imageKey);
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
imageView.setImageResource(R.drawable.ic_launcher);
new DownloadImageTaskViaWeb(imageView).execute(avatarURL);
}
}
private void addBitmapToMemoryCache(String key, Bitmap bitmap) {
if (getBitmapFromMemCache(key) == null) {
mMemoryCache.put(key, bitmap);
}
}
private Bitmap getBitmapFromMemCache(String key) {
return mMemoryCache.get(key);
}
/* a background process that opens a http stream and decodes a web image. */
class DownloadImageTaskViaWeb extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTaskViaWeb(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
addBitmapToMemoryCache(String.valueOf(urldisplay), mIcon);
return mIcon;
}
/* after decoding we update the view on the mainUI */
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
Views are reused for performance with Adapters. You should use another approch .
You have to have a class holder which reuse your views. In your case you class should be something like this:
public class MoviesAdapter extends ArrayAdapter<ParkCinema> {
private ArrayList<ParkCinema> movieDataItems;
private Activity context;
public MoviesAdapter(Activity context, int textViewResourceId, ArrayList<ParkCinema> movieDataItems) {
super(context, textViewResourceId, movieDataItems);
this.context = context;
this.movieDataItems = movieDataItems;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.movie_data_row, null);
holder = new ViewHolder();
holder.imageView = (BarImageView) convertView.findViewById(R.id.movie_thumb_icon);
} else {
holder = (ViewHolder) convertView.getTag();
}
ParkCinema movie = movieDataItems.get(position);
if (movie!=null){
String url = movie.poster();
if (url!=null) {
Bitmap bitmap = fetchBitmapFromCache(url);
if (bitmap==null) {
new BitmapDownloaderTask(imageView).execute(url);
}
else {
imageView.setImageBitmap(bitmap);
}
}
}
return convertView;
}
private LinkedHashMap<String, Bitmap> bitmapCache = new LinkedHashMap<String, Bitmap>();
private void addBitmapToCache(String url, Bitmap bitmap) {
if (bitmap != null) {
synchronized (bitmapCache) {
bitmapCache.put(url, bitmap);
}
}
}
private Bitmap fetchBitmapFromCache(String url) {
synchronized (bitmapCache) {
final Bitmap bitmap = bitmapCache.get(url);
if (bitmap != null) {
return bitmap;
}
}
return null;
public static class ViewHolder {
ImageView imageView;
}
}
I have spent hours trying to figure this one out as well...Thanks to Steven Byle's solution...
Here is my solution to something similar when a user selects an item from a list:
adapter.setSelectedIndex(position);
then in the custom adapter:
public void setSelectedIndex(int ind)
{
selectedIndex = ind;
notifyDataSetChanged();
}
and then finally in the getView method of the adapter:
if(selectedIndex!= -1 && position == selectedIndex)
{
holder.tab.setBackgroundColor(Color.BLACK);
}
else{
holder.tab.setBackgroundColor(Color.DKGRAY);
}
So in conclusion make sure you assign default values
In my case i used Picasso library instead of AsyncTask for downloading image.
enter link description here
Also write if else condition, that is set null to image if url is not available
instead of using the convertview object create a new view each time.
View localView = ((LayoutInflater)parentscreen.getSystemService("layout_inflater")).inflate(R.layout.activity_list_row, null);
By inflating as above.

Load asynchronous images in listView

I want to load images from a server, AFTER loading the data in a list view.
I know that a lot of topics existing for this problem but I haven't found the solution...
So this is my code :
//asyncTackClass for loadingpictures
public class LoadImagesThread extends AsyncTask<Bundle, Void, Bitmap> {
private ImageView view;
private Bitmap bm;
private Context context;
private final WeakReference<ImageView> imageViewReference;
private final String BUNDLE_URL = "url";
private final String BUNDLE_NAME = "name";
private final String BUNDLE_BM = "bm";
public LoadImagesThread(Context context, ImageView view) {
this.context=context;
imageViewReference = new WeakReference<ImageView>(view);
}
#Override
protected Bitmap doInBackground(Bundle... b) {
Bitmap bm =null;
if (StorageHelper.getBitmap(b[0].getString(BUNDLE_NAME)) != null) { // Check the sdcard
bm = StorageHelper.getBitmap(b[0].getString(BUNDLE_NAME));
Log.w("LoadImagesThread", "Get image from sdcard : "+b[0].getString(BUNDLE_NAME));
} else { // Check the server
bm = ServiceHelper.getBitmapFromURL(b[0].getString(BUNDLE_URL));
StorageHelper.saveBitmap(bm, b[0].getString(BUNDLE_NAME)); // Save image on sdcard
Log.w("LoadImagesThread", "Get image from server : "+b[0].getString(BUNDLE_NAME));
}
return bm;
}
#Override
protected void onPostExecute(final Bitmap bm) {
super.onPostExecute(bm);
if (bm != null){ //if bitmap exists...
view = imageViewReference.get();
// Fade out
Animation fadeOutAnimation = AnimationUtils.loadAnimation(context, R.anim.fadeoutimage);
fadeOutAnimation.setAnimationListener(new AnimationListener() {
public void onAnimationStart(Animation animation) {
}
public void onAnimationRepeat(Animation animation) {
}
public void onAnimationEnd(Animation animation) {
// Fade in
view.setImageBitmap(bm);
Animation fadeInAnimation = AnimationUtils.loadAnimation(context, R.anim.fadeinimage);
view.startAnimation(fadeInAnimation);
}
});
// Launch the fadeout
view.startAnimation(fadeOutAnimation);
}else{ //if not picture, display the default ressource
view.setImageResource(R.drawable.productcarre);
}
}
}
The code is used to display a Bitmap in a ImageView
And this is the adapter:
public class ListViewShoplistStoresAdapter extends BaseAdapter {
private ArrayList<Shop> shopList;
private Activity activity;
private HashMap<Integer, ImageView> views;
private final String BUNDLE_URL = "url";
private final String BUNDLE_NAME = "name";
private final String BUNDLE_POS = "pos";
private final String BUNDLE_ID = "id";
public ListViewShoplistStoresAdapter(Activity activity, ArrayList<Shop> shopList) {
super();
this.activity = activity;
this.shopList = shopList;
this.views = new HashMap<Integer, ImageView>();
}
public int getCount() {
return shopList.size();
}
public Object getItem(int position) {
return shopList.get(position);
}
public long getItemId(int position) {
return shopList.get(position).getId();
}
private class ViewHolder {
public TextView store;
public TextView name;
public ImageView ImageStore;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if(convertView == null) {
view = new ViewHolder();
convertView = inflator.inflate(R.layout.listviewshops, null);
view.store = (TextView) convertView.findViewById(R.id.store);
view.name = (TextView) convertView.findViewById(R.id.name);
view.ImageStore = (ImageView) convertView.findViewById(R.id.imgstore);
convertView.setTag(view);
}else {
view = (ViewHolder) convertView.getTag();
}
Typeface regular=Typeface.createFromAsset(activity.getAssets(), "fonts/RobotoRegular.ttf");
view.store.setTypeface(regular);
Typeface light=Typeface.createFromAsset(activity.getAssets(), "fonts/RobotoLight.ttf");
view.store.setTypeface(light);
Brand brand = StorageHelper.getBrand(activity, shopList.get(position).getBrandId());
if (brand == null) {
Log.e("SetShopInAdapter","Brand null");
Toast.makeText(activity, "Impossible d'afficher la liste de magasins", Toast.LENGTH_LONG).show();
} else {
view.store.setText(brand.getName());
view.name.setText(shopList.get(position).getName());
view.ImageStore.setImageResource(R.drawable.productcarre);
}
Bundle b = new Bundle();
//url of the pict
b.putString(BUNDLE_URL, ServiceHelper.getImageUrl("brand", brand.getName()));
// name of image
b.putString(BUNDLE_NAME, ServiceHelper.getCleanImageName(brand.getName()));
//position in the listView
b.putInt(BUNDLE_POS, position);
//id of the current object
b.putInt(BUNDLE_ID, brand.getId());
//put info in the map in order to display in the onPostExecute
if(views.get(position)==null){
views.put(position, view.ImageStore);
// launch thread
new LoadImagesThread(activity.getApplicationContext(), view.ImageStore).execute(b);
}
return convertView;
}
}
So, when I used a GridView, there were no problems, but when I use a ListView the image is changed only in the first item !
Example:
I want to display product images for "car", "house" and "apple" items.
The code will launch the thread and all images (car then house and finally apple) will be displayed in the first item (the car item)...
And the house and the apple while not have images !!
Do you know what I should do ?
Thanks
There is a lot about this here on SO..
asynchrnous loading like that is called "Lazy Loading"
https://github.com/thest1/LazyList
for full implementation of such a process with list
For loading images in general i recomend this :
https://github.com/nostra13/Android-Universal-Image-Loader
You can use volley to improve in listview performance.
Take a look at this simple example: Android Custom ListView with Image and Text using Volley

Using AsyncTask to load Images in ListView

I have one ListView which can hold an image. It depends if image exists or not in SDCARD.
Here my example code:
public class MainActivity extends Activity {
ListView mListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mListView = new ListView(this);
setContentView(mListView);
String[] arr = new String[] {
"/example/images/1.jpg", "/example/images/2.jpg",
"/example/images/3.jpg", "/example/images/4.jpg",
"/example/images/5.jpg", "/example/images/6.jpg",
"/example/images/7.jpg", "/example/images/8.jpg",
"/example/images/9.jpg", "/example/images/1.jpg",
"/example/images/2.jpg", "/example/images/3.jpg",
"/example/images/4.jpg", "/example/images/5.jpg",
"/example/images/6.jpg", "/example/images/7.jpg",
"/example/images/8.jpg", "/example/images/9.jpg",
"/example/images/1.jpg", "/example/images/2.jpg",
"/example/images/3.jpg", "/example/images/4.jpg",
"/example/images/5.jpg", "/example/images/6.jpg",
"/example/images/7.jpg", "/example/images/8.jpg",
"/example/images/9.jpg", "/example/images/1.jpg",
"/example/images/2.jpg", "/example/images/3.jpg",
"/example/images/4.jpg", "/example/images/5.jpg",
"/example/images/6.jpg", "/example/images/7.jpg",
"/example/images/8.jpg", "/example/images/9.jpg"};
List<String> list = Arrays.asList(arr);
MyAdapter adapter = new MyAdapter(this, R.layout.listitem_imv, list);
mListView.setAdapter(adapter);
}
class MyAdapter extends ArrayAdapter<String>{
List<String> mList;
LayoutInflater mInflater;
int mResource;
public MyAdapter(Context context, int resource,
List<String> objects) {
super(context, resource, objects);
mResource = resource;
mInflater = getLayoutInflater();
mList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if(convertView == null){
view = mInflater.inflate(mResource, null);
}else{
view = convertView;
}
ImageView imageView = (ImageView) view.findViewById(R.id.imv);
TextView textView = (TextView) view.findViewById(R.id.txv);
imageView.setTag(mList.get(position));//tag of imageView == path to image
new LoadImage().execute(imageView);
textView.setText(mList.get(position).toString());
return view;
}
}
class LoadImage extends AsyncTask<Object, Void, Bitmap>{
private ImageView imv;
private String path;
#Override
protected Bitmap doInBackground(Object... params) {
imv = (ImageView) params[0];
path = imv.getTag().toString();
Bitmap bitmap = null;
File file = new File(
Environment.getExternalStorageDirectory().getAbsolutePath() + path);
if(file.exists()){
bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
if(result != null && imv != null){
imv.setVisibility(View.VISIBLE);
imv.setImageBitmap(result);
}else{
imv.setVisibility(View.GONE);
}
}
}
}
The 'sdcard/example/images' directory has the images: 1.jpg, 2.jpg, 3.jpg, 4.jpg, 6.jpg, 7.jpg and 9.jpg.
the expected result is:
But, if I scroll the list quickly, some images are inserted in the wrong items.
It happens due to use of convertView in getView() method.
If I use the following code, the code works fine:
//if(convertView == null){
// view = mInflater.inflate(mResource, null);
//}else{
// view = convertView;
//}
view = mInflater.inflate(mResource, null);
When list scrolled quickly, two asyncTasks can reference one same View, due to use of convertView.
How Can I cancel AsyncTask when the View is no longer visible?(and is useb by another item of ListView)
edit
#Override
protected void onPostExecute(Bitmap result) {
if(result != null && imv != null){
if(imv.getTag().equals(path)){
imv.setVisibility(View.VISIBLE);
imv.setImageBitmap(result);
}else{
imv.setVisibility(View.GONE);
}
}else{
imv.setVisibility(View.GONE);
}
}
You can send in the ImageView to the task constructor and keep a reference to the image path there. Now at onPostExecute, check if the current tag of the ImageView is the same as the one that you started with. If yes, then set the image. If no, don't do anything.
However, this means that the image will be downloaded in any case. You'll just not set the wrong image on the view.
EDIT:
First pass the ImageView to the task constructor:
new LoadImage(imageView).execute()
Then save a reference to the ImageView and image path in LoadImage constructor. It is important to save the path in the constructor and not in doInBackground to ensure that we don't run into multi threading problems. Then at onPostExecute we check the current path.
class LoadImage extends AsyncTask<Object, Void, Bitmap>{
private ImageView imv;
private String path;
public LoadImage(ImageView imv) {
this.imv = imv;
this.path = imv.getTag().toString();
}
#Override
protected Bitmap doInBackground(Object... params) {
Bitmap bitmap = null;
File file = new File(
Environment.getExternalStorageDirectory().getAbsolutePath() + path);
if(file.exists()){
bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
if (!imv.getTag().toString().equals(path)) {
/* The path is not same. This means that this
image view is handled by some other async task.
We don't do anything and return. */
return;
}
if(result != null && imv != null){
imv.setVisibility(View.VISIBLE);
imv.setImageBitmap(result);
}else{
imv.setVisibility(View.GONE);
}
}
}
This Android Developers Blog post will give you a complete reference project for this complete with caching. Just replace the Http access code with SD card file reads.
I hope this helps.
After lot of search I have this working solution.
public class CustomAdapter extends ArrayAdapter<String>{
/*
public CustomAdapter(Context context , String[] video) {
super(context,R.layout.custom_row, video);
}
*/
private final Activity context;
private final String[] video;
static class ViewHolder {
public TextView videoTitle;
public ImageView videoThumbnail;
public int position;
public String path;
}
public CustomAdapter(Activity context, String[] video) {
super(context, R.layout.custom_row, video);
this.context = context;
this.video = video;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater videoInflator = LayoutInflater.from(getContext());
View customView = videoInflator.inflate(R.layout.custom_row, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.position = position;
viewHolder.path = video[position];
viewHolder.videoTitle = (TextView) customView.findViewById(R.id.videoTitle);
viewHolder.videoThumbnail = (ImageView) customView.findViewById(R.id.videoThumbnail);
//rowView.setTag(viewHolder);
//}
customView.setTag(viewHolder);
final String videoItem = video[position];
int index=videoItem.lastIndexOf('/');
String lastString=(videoItem.substring(index +1));
index = lastString.indexOf(".mp4");
lastString=(lastString.substring(0,index));
viewHolder.videoTitle.setText(lastString);
new AsyncTask<ViewHolder, Void, Bitmap>() {
private ViewHolder v;
#Override
protected Bitmap doInBackground(ViewHolder... params) {
v = params[0];
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(videoItem, MediaStore.Images.Thumbnails.MINI_KIND);
return thumb;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (v.position == position) {
// If this item hasn't been recycled already, hide the
// progress and set and show the image
v.videoThumbnail.setImageBitmap(result);
}
}
}.execute(viewHolder);
return customView;
}
}
Maybe you should try:
view = mInflater.inflate(mResource,parent,null);
Check this blog it explains the similar issue:
http://www.doubleencore.com/2013/05/layout-inflation-as-intended/
What I would do (unless you have thousands of images):
1. create a data structure - a simple class holding a String name to be displayed and a bitmap
2. create an adapter for it
3. in the getView method assign the correct bitmap to the correct ImageView.
In your case though you can create a similar data structure but holding not a bitmap but an AsyncTask. Anyway you need to bind the asynctask to the string into one item. An array (or arraylist) of such items will be fed to your adapter. Displayed will be an imageview and a textview.
AsyncTask can be cancelled with cancel().
Hey I found the solution to this problem just use following function instead of your function
#Override
protected void onPostExecute(Bitmap result) {
if (!imv.getTag().toString().equals(rec_id)) {
return;
}
if(result != null && imv != null){
int index = id.indexOf(imv.getTag().toString());
if(list.getFirstVisiblePosition()<=index && index<=list.getLastVisiblePosition())
{
imv.setVisibility(View.VISIBLE);
imv.setImageBitmap(result);
}
}else{
imv.setImageBitmap(icon);
imv.setVisibility(View.GONE);
}
}
Here list is the object of listview. Just pass your list view object to your adapter and paste this function instead of your onPostExecute function.

Categories

Resources