2

Following this answer on how to set a ringtone in an android activity, I'm using this code:

File k = new File(path, "mysong.mp3"); // path is a file to /sdcard/media/ringtone

ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "My Song title");
values.put(MediaStore.MediaColumns.SIZE, 215454);
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.Audio.Media.ARTIST, "Madonna");
values.put(MediaStore.Audio.Media.DURATION, 230);
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
values.put(MediaStore.Audio.Media.IS_ALARM, false);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);

//Insert it into the database
Uri uri = MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath());
Uri newUri = main.getContentResolver().insert(uri, values);

RingtoneManager.setActualDefaultRingtoneUri(
  myActivity,
  RingtoneManager.TYPE_RINGTONE,
  newUri
);

However, this creates a new entry in my Content Resolver every time I run my program. How can I check if a Uri is already present in the Content Resolver? I couldn't find anything in the documentations.

Community
  • 1
  • 1
iomartin
  • 3,149
  • 9
  • 31
  • 47

3 Answers3

5

A Content Resolver is just something that handles the interaction between your app and a content provider.

You should be looking at content providers, and the MediaStore content provider in particular.

What you're doing when you call

Uri newUri = main.getContentResolver().insert(uri, values);

Is inserting a new row into MediaStore. newUri points to this row. You can get the row's _ID value by calling

long newID=ContentUris.parseId(newUri);

However, I think what you're asking is "how do I tell if I've already added a song to MediaStore?" I would suggest that you do a query on MediaStore. See ContentResolver.query().

If I was doing it, I'd query on MediaColumns.DATA, to see if you've previously written to that file. Beyond that, you'll have to decide what constitutes a ringtone that's "already present".

JafarKhQ
  • 8,676
  • 3
  • 35
  • 45
Joe Malin
  • 8,621
  • 1
  • 23
  • 18
2

You can simply query this Uri

Cursor c = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
if (c.getCount == 1) {
    // already inserted, update this row or do sth else
} else {
    // row does not exist, you can insert or do sth else
}
Mike
  • 819
  • 1
  • 8
  • 14
0

If you don't want to insert new values use ContentResolver.update() with a suitable where clause to update existing values.

Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134