Android SDK documentation says that startManagingCursor()
method is depracated:
This method is deprecated. Use the new CursorLoader class with LoaderManager instead; this is also available on older platforms through the Android compatibility package. This method allows the activity to take care of managing the given Cursor's lifecycle for you based on the activity's lifecycle. That is, when the activity is stopped it will automatically call deactivate() on the given Cursor, and when it is later restarted it will call requery() for you. When the activity is destroyed, all managed Cursors will be closed automatically. If you are targeting HONEYCOMB or later, consider instead using LoaderManager instead, available via getLoaderManager()
So I would like to use CursorLoader
. But how can I use it with custom CursorAdapter
and without ContentProvider
, when I needs URI in constructor of CursorLoader
?
I wrote a simple CursorLoader that does not need a content provider:
It only needs the
AsyncTaskLoader
class. Either the one in Android 3.0 or higher, or the one that comes with the compatibility package.I also wrote a
ListLoader
which is compatible with theLoadManager
and is used to retrieve a genericjava.util.List
collection.A third option would be to simply override
loadInBackground
:This will also take care of re-querying your cursor when the database changes.
Only caveat: You'll have to define another observer, since Google in it's infinite wisdom decided to make theirs package private. If you put the class into the same package as the original one (or the compat one) you can actually use the original observer. The observer is a very lightweight object and isn't used anywhere else, so this doesn't make much of a difference.
Write your own loader that uses your database class instead of a content provider. The easiest way is just to take the source of the
CursorLoader
class from the compatibility library, and replace provider queries with queries to your own db helper class.The SimpleCursorLoader is a simple solution, however it doesn't support updating the loader when the data changes. CommonsWare has a loaderex library that adds a SQLiteCursorLoader and supports re-query on data changes.
https://github.com/commonsguy/cwac-loaderex
The third option proposed by Timo Ohr, together with the comments by Yeung, provide the simplest answer (Occam's razor). Below is an example of a complete class that works for me. There are two rules for using this class.
Any time that the underlying database changes (e.g., after an insert or delete), make sure to call
where myUri is the same one returned from your implementation of method getContentUri().
Here is the code for the class that I used: