iomartin
iomartin

Reputation: 3199

Check if Content Resolver has value

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.

Upvotes: 2

Views: 3178

Answers (3)

Joe Malin
Joe Malin

Reputation: 8641

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".

Upvotes: 5

Mike
Mike

Reputation: 819

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
}

Upvotes: 2

Diego Torres Milano
Diego Torres Milano

Reputation: 69358

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

Upvotes: 0

Related Questions