This question would be a follow up from the one asked Content Resolver vs Cursor Loader
Where the answer clearly states how to insert records into a sqlite Db using a Content Resolver . My question is the following :
Can i use a loader(Normal Loader) to implement this functionality ?
eg :
public Loader<Cursor> onCreateLoader(int id, Bundle bundle) {
switch (id) {
case AppConstants.LOADER_ADD_FAV_PHONE_NUM:
ContentValues values = new ContentValues();
values.put(DBHelper.TM_DB_COLUMN_PHONE_NUMBER,
directionOrder);
values.put(TransitMeDBHelper.TM_DB_COLUMN_NAME_ID, selectionArgs[0]);
Uri insertFavStop =getContentResolver().insert(TransitMeContentProvider.CONTENT_URI_INSERT_FAV_PHONE,
values);
break;
}
return null;
}
Would this run the functionality in the Main UI thread or a worker Thread . I understand that i would not receive callbacks for this as the content resolver will return a URI instead of the cursor containing data .
I tried running this code but it behaves kind of wierd .. Duplicate inserts are recorded and its not consistient , Could someone show me to some right resource which uses a Loader to do Insert operations ( I have seen many examples with query examples and it works like a charm :) )
Thank you for your time .
Can i use a loader(Normal Loader) to implement this functionality ?
You can't use a default CursorLoader to insert data. If you implement your own Loader you could probably use the loadInBackground method to do the insert but that will make your code awkward at best(and I don't know if it will actually work).
Would this run the functionality in the Main UI thread or a worker
Thread . I understand that i would not receive callbacks for this as
the content resolver will return a URI instead of the cursor
containing data .
The loader callbacks will run on the thread where they are implemented(the UI main thread most likely) so you're doing the getContentResolver().insert() on the main UI thread with the possibility of blocking the main UI thread.
I tried running this code but it behaves kind of wierd .. Duplicate
inserts are recorded and its not consistient ,
Have you tested how many times is the onCreateLoader method called?
Could someone show me to some right resource which uses a Loader to do
Insert operations ( I have seen many examples with query examples and
it works like a charm :) )
Don't use/try to use a Loader to insert data in the ContentProvider/Database. It works like a charm for queries because the loaders were designed to load data from a data source(not insert data), that is their purpose. If you want to insert data use an AsyncTask(also have a look at AsyncQueryhandler), a regular thread.
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 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'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);
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
I'm having issues with multithreading in my application. I know there are many posts on Threads/AsyncTasks/etc, but none seem to address my specific problem.
Basically, I get a query string in my search Activity, then send it to my results Activity, where the string is used as a SQL query, the results are returned as an array of JSON objects, then I display these objects in a ListView (which is part of the results Activity). All of my SQL connection and retrieval is done in a separate class that I call at the start of the results Activity.
MySQLRetrieve data = new MySQLRetrieve();
ArrayList<Tile> tiles = data.getResults(nameValuePairs, isLocationSearch);
The above code is how I get the SQL response and convert into an ArrayList, which I then use the populate my ListView with. getResults() takes care of all of this.
I already have separate threads working to download images into the ListView, but what I can't get to work is getting the SQL query and result to run in it's own Thread. What I want to achieve is this:
User enters search query in search Activity.
Intent is sent to results Activity, and it starts immediately.
ProgressDialog (just the animated spinner thing, not a loading bar) displays while the SQL query is taking place.
ListView populates with objects from the JSON array, lazy loading images as they come.
I have steps 1,2, and 4 working well, but 3 is the problem. I've looked up AsyncTasks, which seem to be the answer, but I just can't get them to work. Does anyone have a solution to this problem? I need to do this, so when starting the results Activity, the UI changes immediately to the results Activity and doesn't have to wait until the SQL response is returned.
And yes, I've already read the painless-threading post.
Thank you.
I would recommend against creating that ArrayList<Tile> to reduce memory consumption (and code size) and instead directly bind the SQLite Cursor to the ListView using a CursorAdapter.
That alone might just increase the performance enough that you don't need to do any async loading.
If you still want async loading, check out the LoaderManager framework (available since Android 3.0/ API level 11, with Android support package down to 1.6/4) which will automagically do asynchronous loading of your Cursor -- either using the built-in CursorLoader (if you happen to have a ContentProvider), or the SimpleCursorLoader created by a fellow SO user (if you don't).