Reputation: 8916
I have some images in database and I'd like to show them in GridView
.
Here is my function for get Bitmaps
from Database
public Bitmap getBitmaps(String tableName, int id, int index) {
String selectQuery = "SELECT * FROM " + tableName + " WHERE "
+ BaseColumns._ID + " = " + id;
Cursor cursor = mDatabase.rawQuery(selectQuery, null);
cursor.moveToFirst();
byte[] byteArray = cursor.getBlob(index);
return BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
}
And here is my GridView
's Adapter
public View getView(final int position, View convertView,
ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
//..
} else {
//..
}
new AsyncTask<ViewHolder, Void, Bitmap>() {
private ViewHolder v;
@Override
protected Bitmap doInBackground(ViewHolder... params) {
v = params[0];
return getBitmaps(tableName, id,index);
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (v.position == position) {
v.image.setImageBitmap(result);
}
}
}.execute(viewHolder);
return convertView;
}
Now I have a problem:
For example I have more than 20 items in my GridView
. When I scroll down to the end of the list it takes 1 or 2 seconds (or more seconds if list get larger) to load the image of a certain position . Same problem appears if I scroll to the top of the list .
Now how can I optimize my code to scroll smooth and fast?
Upvotes: 0
Views: 183
Reputation: 18977
You must change your approach for example create a ImageLoader class and pass your request to it. in the ImageLoader create an in memory cache LRUCache then if the request is in the cache just return it if it is not load from DB and then set it for viewholder
. for each viewholder
set a tag that is equal to its position then when you have load it check the tag of viewholder
and see if it is equal to the image position that you have just loaded or not, if it is equal set the image else that means the view holder has been recycled. Keep viewholder
reference as a weakreference
and whenever your image is ready check the holder to see if it is null or not.
further optimization also possible and that is for example recycling the bitmap
, you can read the document to see how it is implemented.
Happy Coding :-)
Upvotes: 1