Moving a File In The Android MediaStore

September 25, 2013

When you move or copy a media file in Android, any app that access it via the MediaStore will not automatically be updated. In one of my previous articles I talked about querying and manipulating Android’s MediaStore, and the cost of doing a full scan of the file system to check for changes. Luckily, there’s an easier way to update the file’s location: use ContentResolver’s update() method.

ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, newPath);
int rows = context.getContentResolver().update(
  MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values,
  MediaStore.MediaColumns.DATA + "='" + oldPath + "'", null
);

In this example I’m moving an audio file. Because the path to the actual file is stored in the MediaStore.MediaColumns.DATA column, I want to query on it and change it. The update() method uses ContentValues to make changes to the MediaStore, and since I only want to update the DATA column, I put the new file path with the appropriate key. Here I’m just concatenating string to build my selection parameter, so the last parameter is left null. The function returns an integer of the rows that were affected, and can be used to verify that you’re querying and updating the correct row.

As pointed out by a commenter in a previous post, update(), as well as any other function on a ContentResolver, is synchronous. This means that if called on the UI thread it will block until it completes. While, in my experience, updating one row is extremely fast, you should put all potentially costly method calls, especially ones that do not directly affect the UI, in a separate thread.