Android

How to delete a file from mediastore’s database or how to notify mediastore that a content is deleted ?

How to delete a file from mediastore’s database or how to notify mediastore that a content is deleted ?
How to delete a file from mediastore’s database or how to notify mediastore that a content is deleted ?

Filename still showing on device even after you delete it ?

Like updating mediastore database with filename and path after a new file is added to device, it is also important to remove the file from mediastore database whenever we delete a file from an android device.

Otherwise mediastore hold the information about the removed content and cause conflict with other apps or our apps whenever we access the mediastore database

Example : Imagine our user delete an audio file using app and  code doesn’t contain any method for updating mediastore, then again in next activity we reload all audio contents to a listview.

This newly generated listview still contains the deleted filename and user wonders why its there and if he tries to play it, then app may crash.

PS: It will automatically update database after the next bootup .

So to overcome this issue we need to notify mediastore about the deleted content.

Sample code to delete file an audio file from mediastore

 

public void remove(int position) 
  {
      Context mContext;
      //remove item from database, recyclerview and storage

      //delete file from storage
      File file = new File(getItem(position).getFilePath());

      file.delete();

      File n = new File (getItem(position).getName());

      Toast.makeText(
          mContext,
          String.format(
              mContext.getString(R.string.toast_file_delete),
              getItem(position).getName()),
          Toast.LENGTH_SHORT).show();

      String mFilePath = 
      Environment.getExternalStorageDirectory().getAbsolutePath();
      mFilePath += "/Audio/MP3Cutter_Recordings/" + n;


      Uri rootUri = 
      MediaStore.Audio.Media.getContentUriForPath( mFilePath );  // Change file types here

      mContext.getContentResolver().delete( rootUri,
      MediaStore.MediaColumns.DATA + "=?", new String[]{ mFilePath } );

  }