When to use cursor loaders? - android

When I use SQLite to bring my data and use cursor and adapters, should I use cursor Loaders??. Is this the best practice?. Im not quite clear when to use cursor loaders. Should I use it only if my app shares data with other apps?. My question comes because it have been really annoying for me using cursors + adapters + listView; sometimes the notifyDataSetChanged works, sometimes not, so it have been really tricky sometimes. I start reading about cursor loaders but Im not sure if this is a work around for this in particular or if I can use it as a work around.
Any clarification will be really appreciated!!
Thanks guys.

Use Loaders to ensure that all cursor operations are done asynchronously, thus eliminating the possibility of blocking the UI thread.
When using CursorAdapter donĀ“t use notifyDataSetChanged instead use:
db.updateData();
yourCursor = db.getData();
yourAdapter.changeCursor(yourCursor);

Related

What is the best way to use the insert, delete and update from an Content Provider?

I am spinning my head around this theme for quite some time. I don't have much experience with Android and I'm trying to code everything using the best approach I can.
I successfuly created a Content Provider to wrap my SQLite and some Loaders to query the Data. It works fine, but I'm having some problems deciding how to insert, delete and update outside of the main Thread.
I implemented various AsyncTasks to manage these operations and the results seems nice.
But is this the right approach or am I missing something here?
Is there any special class or pattern out there that I never heard of?
It would be nice if anybody could point me to some direction.
Tks
You can use an AsyncQueryHandler. Pretty much exactly what you've done using AsyncTask, but all the heavy lifting is already dealt with.
Assuming your Content Provider is all good, basically all you really need to do is (for an update):
AsyncQueryHandler handler = new AsyncQueryHandler(ctx.getContentResolver());
final ContentValues cv = new ContentValues();
values.put(column, data);
handler.startUpdate(-1, null, uriOfDatabase, cv, selection, selectionArgs);
See the documentation here

Is it possible to load a dropdown box in Android with items from a SQLite table? How?

I'm recoding an application for the Android platform. I'd like to have a dropdown box populated with items in a user editable table. Is this "easily done" in Android?
yes,it is easily done by using spinner.
try following code
int i=0;
Spinner sp1=(Spinner)findViewById(R.id.spinner1);
Dbhelper db1=new Dbhelper(this);
SQLiteDatabase db=db1.getReadableDatabase();
Cursor c1=db.rawQuery("select accNo from Account4 where bankName='"+str+"'",null);
acc=new String[c1.getCount()];
while(c1.moveToNext()){
acc[i]=c1.getString(c1.getColumnIndex("accNo"));
i++;
}
ArrayAdapter<String> adp=new ArrayAdapter<String(this,android.R.layout.simple_spinner_dropdown_item,acc);
sp1.setAdapter(adp);
c1.close();
db.close();
First of all, I suggest you use the LoaderManager and Loader in order to operate with your database. If you just use the straightforward approach as suggested by user3355820, you will face terrible consequences with your application lifecycle (cursor leak and subsequent ineffective queries to your database on Activity recreation are the lesser of possible vile things).
So, first of all, read Life before Loaders Pt.1 - there are three parts of this article in this awesome blog, and I suggest you read all of them. It will help you understand the conception of Loader and what you should not do.
Then, read CursorLoader without ContentProvider. This will help you to build your own Loader without some excessive (in your usecase) things like ContentProvider.
To populate your dropbox with user data, just wrap the results of your custom CursorLoader in simple SpinnerAdapter implementation, set your Spinner adapter to your adapter implementation and you're all chocolate :)
And finally finally :), if you'd like some dirty code examples, you can take a look at my github repo, it contains some basic implementation of the pattern I introduced to you above (this is pending project, and things are not yet finished, but basic CRUD works).

Writing inside a cursor android

while reading the documentation on Cursor here I read that cursor provides read/write access. I had gone through the API methods of Cursor but there is no setter method available to write into the Cursor. It would be of great help if you could provide me with code snippet. Thanks in advance
I think that's a bug in the documentation. You are quite right that there are no Cursor methods to modify the underlying data.
If you do try to modify the underlying data (by executing SQL statements, for example) while iterating over the data using a Cursor, bad things happen. If you need to make changes, you should keep a separate record of what you need to change whilst iterating with the Cursor, and then apply those changes separately once the Cursor is safely closed.

Utterly confused about loading SQLite data in Honeycomb (Android)

I am new to android development and I've hit a hurdle when trying to load SQLite data to populate a ListFragment. In previous versions of android one made a new instance of the cursor class, made an SQLite query to place the cursor in the appropriate position, called startManagingCursor, made a new SimpleCursorAdapter and finally called setListAdapter. Pretty darn simple (too bad about the UI thread)!
Now almost all of these methods are deprecated and I have no idea how to populate my poor ListView. The documentation says I should use CursorLoader but here on StackOverflow people advise against using it for SQLite queries. How do I tell my cursor to populate the ListView?
Thanks a lot in advance!
You need to convert you DbAdapter into a Content Provider if you want to use CursorLoaders. and put android:exported= false as a property of your content provider so that it is private. Android team is favoring this approach as they say Content Provider is better suited to handle logic. That is why they are bent on deprecating our old ways( was hard on me too). But I have changed my dbadapters to content providers and now gleefully using cursor loaders( they are too cool not to be used). Try it, generally you will do fine with some more boilerplate code of Content Providers in adition to that of DBadapter and sqliteHelper. GO for it!

ListView update on insert, edit, delete notifyDataSetChanged() not working

I have a ListView bound to a SimpleCursorAdapter, and I want it to refresh when I modify the database (by inserting, updating or deleting rows). cursor.notifyDataSetChanged() has no effect (it's called on the UI thread) and ListView.removeViewAt(int) throws an UnsupportedOperationException.
What am I supposed to do on Android to get such a basic behavior?
Note that the database is correctly affected and the modification is shown when I restart the activity. But restarting the activity is not an option here, and changing the ListView adapter is the last resource here, since it's a hack and can't guarantee a smooth transition
DISCLAIMER
Quite basic question, asked millions of times and answered zero.
Please, do not answer if you have never done this in your code, don't ask for mine, and don't bother with try this or try that. Only answer if you know how it's done
From API >= 11 the way to do this is using a CursorLoader, this is also included in the Android Compatibility Library, so you can also use this if you are targeting a previous Android version. CursorLoader will make the query in a background thread and return you the cursor. You will need to implement a ContentProvider. You can read the documentation to get an idea of how to use it. Basically you init a loader and then you restart it when you know data has changed. In the callback you just swap the cursor of your adapter.
Or you can just use requery() on the Cursor. The adapter will get automatically notified of the changes. This method is deprecated now and, of course, it's not the recommended way.

Categories

Resources