CRUD using LoaderManager and CursorAdapter - android

I have a MyListFragment implementation which uses MyCursorAdapter. As the names suggest, they both extend the respective Android classes.
I read through this Loader/LoaderManager tutorial. So, now my query happens in
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(blah1, blah2, blah3, blah4, blah5, blah6);
}
and the LoaderManager along with the Loader takes care of when to re-query and update, runs separate threads for queries, synchronize without having me to worry about it. So far so good.
I have 2 questions:
1) I have implemented a MyContentProvider. Where does this come into picture?
-> It seems that the above new CursorLoader(......) makes the query through the MyContentProvider since it uses the URI as the first argument.
2) I also need to delete / update / insert items in the list. Should I just call my the respective methods from MyContentProvider inside MyListFragment at the desired places? If yes, then can I also load the items manually, without having the loader handle it? If not, then what is the right way to do it? I did not find any information online. Any pointers appreciated.

Yes, thats correct it will call the query method in MyContentProvider with the arguments used in the CursorLoader constructor.
If I understood that correctly the answer is yes you can just call the MyContentProvider methods as long as they are calling ContentResolver.notifyChange() as it will cause the CursorLoader to get a new cursor (this is the whole point of using CursorLoader). When using CursorLoader you should avoid manually changing the data at all if you can so as to allow what is shown to always reflect the current set of data coming from MyContentProvider.

Related

database operation in android loader

I'm using a LoaderManager, the onCreateLoader method creates a new CursorLoader.
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle data) {
return new CursorLoader(context, CONTENT_URI, PROJECTION,
null, null, null);
}
Only after loading is finished in onLoadFinished() the UI is updated.
Every time I load the cusor I also need to do some database manipulation like building up a new sort index. This cannot be done asynchronously because the UI depends on this.
Is there a way to do such db operation within the loader? Or what is the best design for this problem?
As per your question you are loading your data in from database using loader and content provider
also you are working on sorting type of thing which can change the order of item in database...
So, the best way I suggest as per my experience in this type of application of do this of index sorting operation in UI only util user leave the screen...
So, In you activity of fragment override onStop method and update data indexes in database based on sorting priorities or numbers...
and after updating data to content provider just notify URI for change..
hope my point is clear to you..
Loaders were designed specifically with optimizing database access in mind. This operation does not care about updating the UI and hence has no interest in providing progress information. While it is possible (and I use this loosely), to update the UI from a loader, you should avoid this as the Loader is a wrong tool for this job. Forcing a Loader to provide progress information would break the paradigm. The Loader is expected to return only after the etire operation is complete. Instead, if you want to update the UI while doing the querying, then you should use an AsyncTask.
If you HAVE to use a Loader, then you can find a workaround here at Update progressbar from AsyncTaskLoader?. But again, since from your question, it looks like you are open to alternatives, use the AsyncTask if you need updates or you can stick to Java threads.

When to use a Custom CursorLoader?

In my app I want to show a list of apps that I have placed in an resource file.
I parse the XML(resource) file and then save the value in a SQLiteDatabase. I have implemented my Database inside a ContentProvider. What I want to know is do I need a Custom CursorLoader (should I extend CursorLoader?)? or will CursorLoader itself will be sufficient. I have seen an example, but in this no ContentProvider has been used.
Can someone explain when should I implement a Custom CursorLoader as against using the original one?
(A little unrelated) Also what would be the best practice, to implement a database with or without a ContentProvider?
Thanks in Advance!
There are many ways to implement it -
If using a ContentProvider there is no need to extend the CursorLoader.
If not using a ContentProvider and using a SQLiteDatabase instead, we can extend the CursorLoader with our Custom-Loader and override the loadInBackground() method of CursorLoader and instead of querying the ContentProvider we can query the SQLiteDatabase.
While using a SQLiteDatabase we can extend AsyncTaskLoader, however, this is more tedious method than one specified in 2.

Disable notifications on a ContentProvider URI

I'm looking for a way to suspend notifications on a given ContentProvider's Uri. The use case is:
An Activity is bound to a CursorAdapter through a CursorLoader.
A Service may do a lot of batch, single-row updates on a ContentProvider.
The CursorLoader will reload its content on every row update, as the ContentProvider notifies listeners by ContentResolver#notifyChange.
Since I cannot edit the ContentProvider, and I have no control over the batch queries execution, is there a way to suspend notifications on a Uri (in the executing Service) until all of the ContentProvider-managed queries have been executed? I need this in order to avoid the flickering caused by the continuous requerying of the CursorLoader.
You cannot disable this mechanism in your Service. But you should try to batch them by using ContentProviderOperations.
I've written an introductory post about ContentProviderOperations and two additional posts covering the methods withYieldAllowed() and withBackReference() respectively.
Especially the latter one should be of interest for what you've described here.
With ContentProviderOperations you can batch multiple updates and inserts. If you then call applyBatch() on your ContentResolver object the ContentProvider executes them all at once.
Now I've never used Nicolas Klein's generator but since he is a very, very proficient Android developer and works at Google, I bet that the generated code makes use of transactions and calls notifyChange() only once for the complete batch at the end.
Exactly what you need.
Can you substitute your own ContentResolver?
You may try extends ContentResolver with your own class then and you will may override method notifyChange and realize your logic there.
In your Content provider class, inside query() method before returning the cursor, just comment the code which looks something like this
cursor.setNotificationUri(getContext().getContentResolver(), uri);

CursorLoader - obtain information about what has changed in db

I use standard android ContentProvider and CursorLoader from support library.
I am looking for best approach for obtain information about what has changed in database.
I know that I can read and compare cursor in function:
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
}
but reading all records is probably not good solution.
Do you know good solution for this problem?
If you use a content provider, you abstract away all the changes made to the underlying database by implementing CRUD methods to insert, update, delete or retrieve an item in the database.
Sending a broadcast from the methods which you are interested would be an option to get notified of the changes being made to the database.
I recall that I had used this method to count the number of items added to the database during a refresh cycle.
Optionally you can send the Uri of the changed item as an intent extra to get a reference to the row in the database that has been changed.
Additionally you can declare a global variable to enable or disable these broadcasts to fire only during situations of interest to us.

android - CursorLoader & SQLite without Content Provider

I know this has been discussed yet I wanted to ask about the current state of the matter. Do i have to create a ContentProvider to use CursorLoader in connection with a sqlite database?
I found
CursorLoader usage without ContentProvider
Looks exactly what I was hoping for yet as Emmby commented
Users should be aware of one limitation, which is that it has no mechanism to refresh on data changes (as Loaders are supposed to do)
So another solution is mentioned
https://github.com/commonsguy/cwac-loaderex
yet again some drawback is pointed out
However, to make use of the automatic re-querying, you need to use the same loader for the UI as well as for the updates, limiting its usability for background services.
Of course when using LoaderManager we want to get all the benefits for which it was introduced. So my question is if there is a way to use LoaderManager in connection with a sqlite database without having to implement a content provider yet have all the benefits of it.
Thanks
The two implementations you mention in your post both offer all of the benefits of the CursorLoader except the ability to receive notifications when the underlying content changes.
I've been looking into this a lot recently and I can confidently tell you that the Android API currently does not provide a means of doing this with only a raw SQLiteDatabase (it only provides the ContentResolver#notifyChange() and Cursor#setNotificationUri() methods, which are used to notify all Cursors registered under a certain notification Uri).
That said, your options right now are to:
Implement an observer yourself that is capable of receiving notifications from the SQLiteDatabase when the content changes, and is somehow able to relay these notifications to all existing Loaders in your application. I wrote a pretty extensive blog post on how to implement Loaders that might come in handy if you wish to take on this challenge. Or...
Use Mark Murphy's LoaderEx library and only make database modifications using the AsyncTask operations his library provides. Note that the reason why his tasks refresh the Loader is because they call onContentChanged on the Loader immediately after the insertion/update/delete is performed, effectively telling the Loader that the content has changed and that it should refresh its data.
Just use a ContentProvider with a CursorLoader and you can use the ContentResolver#notifyChange() method to notify the CursorLoader that a content change has occurred.
I'm trying to figure out a better solution, and I'll report back in the future if I ever find/implement one, but for now these will have to do.
Here is my solution, in my onCreateLoader
{
Uri u = Uri.parse("content://what_string_you_want");
return new CursorLoader(this, yourURI, projection, null, null, null) {
private final ForceLoadContentObserver mObserver = new ForceLoadContentObserver();
#Override
public Cursor loadInBackground() {
Cursor c = YOUR_DATABASE.doYourQuery(...);
if (c != null) {
// Ensure the cursor window is filled
c.getCount();
c.registerContentObserver(mObserver);
}
c.setNotificationUri(getContext().getContentResolver(), getUri());
return c;
}
};
}
After the code that will change DB, add
getContentResolver().notifyChange(
Uri.parse("content://same_with_first_string"), null);
how about having a boolean in shared preferences as false .. updating the content when that boolean is true....
and when any of the operations which changes the underlying database .. that boolean will be set to true and as shared preferences you a changelistener you can recieve changes live directly after the relevant methods are called

Categories

Resources