CursorLoader, get URI for local database

user1681358 picture user1681358 · Sep 18, 2012 · Viewed 9.5k times · Source

I'm a newbie android programmer and I recently followed a tutorial which shows how to create a local SQLite database and then access the database by using SQLiteDatabase.rawQuery to return a Cursor. I would like to modify my app to use CursorLoader which is apparently a better way to access the database. My problem is the CursorLoader constructor expects a URI to be given. Do I just input "file:///[path to db]"? Seems a bit messy.

Answer

Julian Suarez picture Julian Suarez · Sep 18, 2012

The reason behind cursor loader accepting a URI is that it expects to query a contentProvider and not a raw database.

So I suggest that you create a content provider which internally uses your database, so that you can use the CursorLoader class directly.

The advantage of using a content provider is that it encapsulates better your data and you can easily leverage a lot of apis from android directly.

Here are some guides on how to create a content provider

http://developer.android.com/guide/topics/providers/content-provider-creating.html

http://thinkandroid.wordpress.com/2010/01/13/writing-your-own-contentprovider/

If you choose not to create a ContentProvider you can extend AsyncTaskLoader or the cursor loader directly to query the data the way you want.