Search code examples
javaandroidimagemediastore

Can't get MediaStore.Images.Media after reboot


I developed an app which saves photos inside the app folder (/android/data/[app-folder]/files/Report/[directory]) with some data saved into DESCRIPTION field, here is my code to save image:

ContentValues image = new ContentValues();
image.put(Images.Media.TITLE, directory);
image.put(Images.Media.DISPLAY_NAME, FOTOC_PREFIX_NAME + "_" + directory + "_" + data + ".jpg");
image.put(Images.Media.DESCRIPTION, "EXAMPLE DESC");
image.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
image.put(Images.Media.MIME_TYPE, "image/jpg");
image.put(Images.Media.ORIENTATION, 0);
File parent = imagePath.getParentFile();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
 image.put(MediaStore.Images.ImageColumns.RELATIVE_PATH, parent.getAbsolutePath());
}
image.put(Images.ImageColumns.BUCKET_ID, parent.toString().toLowerCase().hashCode());
image.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, parent.getName().toLowerCase());
image.put(Images.Media.SIZE, imagePath.length());
image.put(Images.Media.DATA, imagePath.getAbsolutePath());
Uri result = getContentResolver().insert(MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY), image);

And then i read data with:

String whereCause = MediaStore.Images.Media.DISPLAY_NAME + " LIKE '%" + UsefullThings.getNameWithoutExtension(photofile.getName()) + "%'";
String[] projection = new String[] {MediaStore.Images.Media.DISPLAY_NAME,MediaStore.Images.Media.DESCRIPTION,MediaStore.Images.Media.TITLE,MediaStore.Images.Media._ID};
 Cursor cursor = getContentResolver().query(MediaStore.Images.Media
                                                            .getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY), projection, whereCause, null, MediaStore.Images.Media._ID);
 if (cursor.getCount() == 1) {
   cursor.moveToFirst();
 }

 String descstring = "";
 try {
  descstring =cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DESCRIPTION));
 }catch(Exception e){
  ....
 }

where photofile is the image. Everything is working fine, but if i reboot my tablet then the same query returns empty cursor.

Can anyone help me? Thanks


Solution

  • app which saves photos inside the app folder (/android/data/[app-folder]/files/Report/[directory])

    You mean /storage/emulated/0/Android/data/[app-folder]/files/Report/[directory] ?

    That is impossible to begin with if you use the MediaStore.

    That is an app specific directory and the MediaStore will not give you insert() uries for that location.

    image.put(MediaStore.Images.ImageColumns.RELATIVE_PATH, parent.getAbsolutePath());

    You should put a relative path in .RELATIVE_PATH. Not a full absolute path as you do now. Also we cannot see what exactly you put in there. Please tell value of parent.getAbsolutePath().