Thursday, May 24, 2012

Getting the Android id from a URI - Content Provider

I've been working quite a bit with Android content providers on a recent project and one thing that keeps coming up is how to determine the android id (_id) of a record that has just been created via a content provider. The insert statement returns the uri pointing to the row that has been created and this URI ends with the key to the object. In other words the URI can tell you the id, all you have to do is parse it.

 An easy way of doing that parsing is shown below.


Uri uri=getContentResolver().insert(ProviderHelper.determineURI(myCarObj), myCarObj.createContentValues());
Log
String carId = uri.getPathSegments().get(1);

Log.d(TAG, "Content inserted at: " + uri);
Log.d(TAG, "Car_id: " + carId);




05-24 13:49:41.290: D/CarProviderTest(11228): Content inserted at: content://com.supercar.edc.android.contentproviders.Car/car/123


05-24 13:49:41.290: D/CarProviderTest(11228): Car_id: 123)



123 is the Android Id (_id) for the record I just created.






No comments:

Post a Comment