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);
Related
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.
I had read the documentation of ContentProvider and quite good number of tutorials\questions but seems there's gap in my head about how could I use the ContentProvider project; the first project which is the ContentProvider from TutorialPoint and it's working fine, I added to my demo project the following statement android:sharedUserId="com.example.mycontentprovider to my AndroidManifest.XML to access the shared DB I had there. Now I want to use the CRUD functions and I'm not sure how to do this, I found one of solutions here is to do such statement Context friendContext = this.createPackageContext("com.example.mycontentprovider",Context.CONTEXT_IGNORE_SECURITY);
Another solution been found is to initialize Intent and start activity and I did as the following:
Intent openMyContentProvider = new Intent("com.example.mycontentprovider",MainActivity.this);
and it gives me error for the arguments and though not sure how to proceed after starting new Activity; Any further requirements or codes will be provided and thanks in advance for your response.
You can use a CursorLoader to read data from the content provider, with the advantage of getting updates when the data in the database changes.
Use ContentResolver for read, insert, update and delete operations. And there is AsyncQueryHandler to help make handling asynchronous ContentResolver queries easier, you can use its on*Complete() callbacks to let the user know the operation was successful. Using AsyncQueryHandler
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.
I want registered callback method using sqlite trigger
for example,
public void printLog(){
Log.i("TAG","1 row added");
}
this method calling after insert any row in sqlite.
Is it possible?
How to do that?
SQLite provides Data Change Notification Callbacks. I don't think that Android exposes them directly but it does have for example CursorAdapter which provides some change notifications.
You can use also use the getContentResolver().registerContentObserver but unfortunately it doesn't tell you what kind of change was made, it could be a delete, insert or update.
If you control the ContentProvider that interfaces with the DB then you could fire an Intent or use getContentResolver().notifyChange to send a special Uri notification that identifies both the table and action. An example Uri you could notify with might be: content://my-authority/change/table-name/insert
But even then you don't know exactly which rows were effected by the change.
Seems like triggers that write to a change log table will guarantee you hear about all changes regardless of where they came from, and you can know the exact id and action that occurred. Unfortunately it means slower inserts/updates/deletes and it means you probably need a Service of some kind to process and delete changes.
I'd love to hear if these is some better solution out there!
You can set content observer this link will help Receives call backs for changes to content http://developer.android.com/reference/android/database/ContentObserver.html
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