Reputation: 165
I currently have an app that can save images from the app to the internal storage to view later. I want to have a gallery of all the images in the app. But if I load 7 or more images into the gridview
the app starts to lag, and it will take some time to load that activity.
So I was wondering how I could optimize this.
Loading images into the ArrayList
:
final ArrayList<ImageItem> imageItems = new ArrayList<>();
//TypedArray imgs = getResources().obtainTypedArray(R.array.image_ids);
for (int i = 1; i < getApplicationContext().fileList().length; i++) {
String[] names = getApplicationContext().fileList();
Log.d("HIER:", names[i]);
Bitmap b = null;
try{
InputStream is = getApplicationContext().openFileInput(names[i]);
b = BitmapFactory.decodeStream(is);
} catch(Exception e){
e.printStackTrace();
}
//arrayList.add(new ImageItem(Bitmap.createScaledBitmap(b, 100, 100, false), names[i]));
arrayList.add(new ImageItem(b, names[i]));
Setting up the gridview
:
gridView = (GridView) findViewById(R.id.gridView);
gridAdapter = new GridViewAdapter(this, R.layout.favorite_item, arrayList);
gridView.setAdapter(gridAdapter);
Upvotes: 1
Views: 280
Reputation: 1180
Best way is to use recent-images library. It is so simple. Just add library dependency to your project and then put below lines to your class. Your adapter is ready, you can set it for your gridview.
RecentImages ri = new RecentImages();
ImageAdapter adapter = ri.getAdapter(MainActivity.this);
It has some option for customizing your query on images.
Upvotes: 0
Reputation: 445
If you are loading lots of files, initialize an empty GridView
when the activity starts, launch an AsyncTask
that loads your images in another thread, and update your GridView
adapter afterwards. When data is loaded, remember to call notifyDatasetChanged()
to update the GridView
.
Example:
public class ImageLoader extends AsyncTask<Void, Void, ArrayList<ImageItem>> {
YourActivity activity;
public ImageLoader(YourActivity activity) {
this.activity = activity;
}
@Override
protected ArrayList<ImageItem> doInBackground(Void... params) {
ArrayList<ImageItem> imageItems = new ArrayList<>();
//load your images
return imageItems;
}
@Override
protected void onPostExecute(ArrayList<ImageItem> imageItems) {
//call a method from your Activity, that updates the Adapter using the retrieved array
activity.update();
}
}
And in your Activity:
public void update(ArrayList<ImageItem> imageItems) {
//update your adapter's data, and refresh the GridView
}
If you will have hundreds of images, it will be better to use multiple Asynctasks, and update each time you load some images, so that whe user would not wait multiple seconds for all files to load
Upvotes: 1