Question

I have seen other SO questions and already tried their solution's but didn't help so i am myself asking

I am facing a problem while loading all images from device in a 'GridView', I am using 'MediaStore' to fetch images and i am quite successfull in that and also i have divided all the images folder wise

My phone is having 1 GB ram so i am able load images without difficulties, But the problem i am facing is that when i use it another device with less then my phone's ram it takes more time to load the images and sometimes it just don't load any image i have already tried using 'AsyncTask' but its not helping.

Below is what i have done so far:

public class DirectoryImagesActivity extends Activity {

private ImageAdapter imageAdapter;

public static String[] arrPath;
private boolean[] thumbnailsselection;
private int ids[];
private int count;
Bundle dirBundle;
String dirName;
public static Bitmap[] imageThumb;
ArrayList<Bitmap> dirBitmap = new ArrayList<Bitmap>();

/**
 * Overrides methods
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.photo_gallery);

    dirBundle = getIntent().getExtras();

    dirName = dirBundle.getString("dir_name");

    String[] projectionFolder = { MediaStore.Images.Media._ID,
            MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
            MediaStore.Images.Media.DATA };
    String selection = MediaStore.Images.Media.BUCKET_DISPLAY_NAME + " = ?";
    String[] selectionArgs = new String[] { dirName };
    @SuppressWarnings("deprecation")
    Cursor mImageCursor = managedQuery(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projectionFolder,
            selection, selectionArgs, null);

    int image_column_index = mImageCursor
            .getColumnIndex(MediaStore.Images.Media._ID);
    this.count = mImageCursor.getCount();
    arrPath = new String[this.count];
    imageThumb = new Bitmap[this.count];
    ids = new int[count];
    this.thumbnailsselection = new boolean[this.count];
    for (int i = 0; i < this.count; i++) {
        mImageCursor.moveToPosition(i);
        ids[i] = mImageCursor.getInt(image_column_index);
        int dataColumnIndex = mImageCursor
                .getColumnIndex(MediaStore.Images.Media.DATA);
        arrPath[i] = mImageCursor.getString(dataColumnIndex);
        int id = mImageCursor.getInt(mImageCursor
                .getColumnIndex(MediaStore.MediaColumns._ID));

        dirBitmap.add(MediaStore.Images.Thumbnails.getThumbnail(
                getContentResolver(), id,
                MediaStore.Images.Thumbnails.MICRO_KIND, null));

    }
    GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
    imageAdapter = new ImageAdapter(this);
    imagegrid.setAdapter(imageAdapter);
    // imagecursor.close();

    final Button selectBtn = (Button) findViewById(R.id.selectBtn);
    selectBtn.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            final int len = thumbnailsselection.length;
            int cnt = 0;
            String selectImages = "";
            for (int i = 0; i < len; i++) {
                if (thumbnailsselection[i]) {
                    cnt++;
                    selectImages = selectImages + arrPath[i] + "|";
                }
            }
            if (cnt == 0) {
                Toast.makeText(getApplicationContext(),
                        "Please select at least one image",
                        Toast.LENGTH_LONG).show();
            } else {

                Log.d("SelectedImages", selectImages);
                Intent i = new Intent();
                i.putExtra("data", selectImages);
                setResult(Activity.RESULT_OK, i);
                finish();
            }
        }
    });
}

@Override
public void onBackPressed() {
    setResult(Activity.RESULT_CANCELED);
    super.onBackPressed();

}

/**
 * Class method
 */

/**
 * This method used to set bitmap.
 * 
 * @param iv
 *            represented ImageView
 * @param id
 *            represented id
 */

public void setBitmap(final ImageView iv, final Bitmap id) {

    new AsyncTask<Void, Void, Bitmap>() {

        @Override
        protected Bitmap doInBackground(Void... params) {

            return id;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            iv.setImageBitmap(result);
        }
    }.execute();
}

/**
 * List adapter
 * 
 * @author tasol
 */

public class ImageAdapter extends BaseAdapter {
    private LayoutInflater mInflater;
    public ImageLoader imageLoader;
    Context context;

    public ImageAdapter(Context context) {
        this.context = context;
        mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        imageLoader = new ImageLoader(context);

    }

    public int getCount() {
        return dirBitmap.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(final int position, View convertView,
            ViewGroup parent) {
        final ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.layout_improved_grid,
                    null);
            holder.imageview = (SquareImageView) convertView
                    .findViewById(R.id.thumbImage);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.imageview.setId(position);

        // holder.imageview.setImageBitmap(imageThumb[position]);
        holder.imageview.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                Toast.makeText(DirectoryImagesActivity.this,
                        "Item Clicked", Toast.LENGTH_LONG).show();

                Intent i = new Intent(getApplicationContext(),
                        FullImageActivity.class); // passing array index
                i.putExtra("id", position);
                startActivity(i);

            }
        });

        try {
            setBitmap(holder.imageview, dirBitmap.get(position));
        } catch (Throwable e) {

        }

        holder.id = position;
        return convertView;
    }
}

/**
 * Inner class
 * 
 * @author tasol
 */
class ViewHolder {
    SquareImageView imageview;
    int id;
}

public static Bitmap convertBitmap(String path) {

    Bitmap bitmap = null;
    BitmapFactory.Options bfOptions = new BitmapFactory.Options();
    bfOptions.inDither = false; // Disable Dithering mode
    bfOptions.inPurgeable = true; // Tell to gc that whether it needs free
                                    // memory, the Bitmap can be cleared
    bfOptions.inInputShareable = true; // Which kind of reference will be
                                        // used to recover the Bitmap data
                                        // after being clear, when it will
                                        // be used in the future
    bfOptions.inTempStorage = new byte[32 * 1024];

    File file = new File(path);
    FileInputStream fs = null;
    try {
        fs = new FileInputStream(file);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    try {
        if (fs != null) {
            bitmap = BitmapFactory.decodeFileDescriptor(fs.getFD(), null,
                    bfOptions);
        }
    } catch (IOException e) {

        e.printStackTrace();
    } finally {
        if (fs != null) {
            try {
                fs.close();
            } catch (IOException e) {

                e.printStackTrace();
            }
        }
    }

    return bitmap;
}

}

If anybody can help me with this thank you in advance

Was it helpful?

Solution

Try this is working solution

1)PhotoGalaryActivity.java

public class PhotoGalaryActivity extends Activity {

    private ImageAdapter imageAdapter;

    private String[] arrPath;
    private boolean[] thumbnailsselection;
    private int ids[];
    private int count;


    /**
     * Overrides methods
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photo_gallery);

        final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
        final String orderBy = MediaStore.Images.Media._ID;
        @SuppressWarnings("deprecation")
        Cursor imagecursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, orderBy);
        int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
        this.count = imagecursor.getCount();
        this.arrPath = new String[this.count];
        ids = new int[count];
        this.thumbnailsselection = new boolean[this.count];
        for (int i = 0; i < this.count; i++) {
            imagecursor.moveToPosition(i);
            ids[i] = imagecursor.getInt(image_column_index);
            int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
            arrPath[i] = imagecursor.getString(dataColumnIndex);
        }
        GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
        imageAdapter = new ImageAdapter();
        imagegrid.setAdapter(imageAdapter);
        imagecursor.close();

        final Button selectBtn = (Button) findViewById(R.id.selectBtn);
        selectBtn.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                final int len = thumbnailsselection.length;
                int cnt = 0;
                String selectImages = "";
                for (int i = 0; i < len; i++) {
                    if (thumbnailsselection[i]) {
                        cnt++;
                        selectImages = selectImages + arrPath[i] + "|";
                    }
                }
                if (cnt == 0) {
                    Toast.makeText(getApplicationContext(), "Please select at least one image", Toast.LENGTH_LONG).show();
                } else {

                    Log.d("SelectedImages", selectImages);
                    Intent i = new Intent();
                    i.putExtra("data", selectImages);
                    setResult(Activity.RESULT_OK, i);
                    finish();
                }
            }
        });
    }
    @Override
    public void onBackPressed() {
        setResult(Activity.RESULT_CANCELED);
        super.onBackPressed();

    }

    /**
     * Class method
     */

    /**
     * This method used to set bitmap.
     * @param iv represented ImageView 
     * @param id represented id
     */

    private void setBitmap(final ImageView iv, final int id) {

        new AsyncTask<Void, Void, Bitmap>() {

            @Override
            protected Bitmap doInBackground(Void... params) {

                return MediaStore.Images.Thumbnails.getThumbnail(getApplicationContext().getContentResolver(), id, MediaStore.Images.Thumbnails.MICRO_KIND, null);
            }

            @Override
            protected void onPostExecute(Bitmap result) {
                super.onPostExecute(result);
                iv.setImageBitmap(result);
            }
        }.execute();
    }


    /**
     * List adapter
     * @author tasol
     */

    public class ImageAdapter extends BaseAdapter {
        private LayoutInflater mInflater;

        public ImageAdapter() {
            mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        public int getCount() {
            return count;
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = mInflater.inflate(R.layout.photo_gallery_item, null);
                holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage);
                holder.checkBox = (CheckBox) convertView.findViewById(R.id.itemCheckBox);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.checkBox.setId(position);
            holder.imageview.setId(position);
            holder.checkBox.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    CheckBox cb = (CheckBox) v;
                    int id = cb.getId();
                    if (thumbnailsselection[id]) {
                        cb.setChecked(false);
                        thumbnailsselection[id] = false;
                    } else {
                        cb.setChecked(true);
                        thumbnailsselection[id] = true;
                    }
                }
            });
            holder.imageview.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    int id = holder.checkBox.getId();
                    if (thumbnailsselection[id]) {
                        holder.checkBox.setChecked(false);
                        thumbnailsselection[id] = false;
                    } else {
                        holder.checkBox.setChecked(true);
                        thumbnailsselection[id] = true;
                    }
                }
            });
            try {
                setBitmap(holder.imageview, ids[position]);
            } catch (Throwable e) {
            }
            holder.checkBox.setChecked(thumbnailsselection[position]);
            holder.id = position;
            return convertView;
        }
    }


    /**
     * Inner class
     * @author tasol
     */
    class ViewHolder {
        ImageView imageview;
        CheckBox checkBox;
        int id;
    }

}

2)photo_gallery.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">
    <ImageView android:id="@+id/thumbImage" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_centerInParent="true" 
        />
    <CheckBox android:id="@+id/itemCheckBox" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_alignParentRight="true"
        android:layout_alignParentTop="true" />
</RelativeLayout>

3)photo_gallery_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">
    <ImageView android:id="@+id/thumbImage" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_centerInParent="true" 
        />
    <CheckBox android:id="@+id/itemCheckBox" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_alignParentRight="true"
        android:layout_alignParentTop="true" />
</RelativeLayout>

OTHER TIPS

As there are many images you are loading you have to implement lazy loading in-order to increase app's performance for other low memory devices. You can refer this library https://github.com/nostra13/Android-Universal-Image-Loader. I hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top