0

Im trying to list out all of images file from internal or external storage using getContentResolver().query(...) and that is work. And the weird thing is, sometimes that method returning an empty cursor, how can be this happen? I also try another suggested here to list out all images from internal or external storage but the result is the same, sometimes returned Cursor is empty. Any idea? Here is my code :

protected Exception doInBackground(Object... params) {
    try {
        Cursor cursor = getImageCursor();
        cursor.moveToFirst();
        mImageSources.clear();

        for (int i = cursor.getCount()-1; i > 0; i--) {
            cursor.moveToPosition(i);
            mImageSources.add(
                    new CameraRollItem(
                            Uri.parse(cursor.getString(1)),
                            cursor.getString(1),
                            cursor.getString(3),
                            i
                    ));
        }
        cursor.close();
    } catch (Exception e) {
        e.printStackTrace();
        return e;
    }
    return null;
}

private Cursor getImageCursor() {
    Cursor cursor = null;
    // It have to be matched with the directory in SDCard
    cursor = mContext
            .getContentResolver()
            .query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
    // if cursor is null, then try to read image from internal memory
    if (cursor == null)
        cursor = mContext
                .getContentResolver()
                .query(MediaStore.Images.Media.INTERNAL_CONTENT_URI, null, null, null, null);

    return cursor;
}
Community
  • 1
  • 1

1 Answers1

0

After waste my hours to solved this problem, I already found the answer. According to Cursor documentation here, do not ever close the cursor if you used reusable cursor. Calling close() method will set the cursor become invalid.