Question

I have used Android's SQLite before but I have always managed rows of data manually, so I never used classes like SimpleCursorAdapter. I want to start using them now, but I need a little help in the code implementation, since it says I HAVE to use a CursorLoader. I decided I'm using SQLiteCursorLoader library.

Here are the details:

I have a table called students in the SQLite database. Also, Student model class and StudentManager controller class. Calling StudentManager#getAll() returns a Cursor containing all the students.

Let's move to the Fragment. I am not using ListFragment for versatility. Anyway, until now I have the following inside onCreate:

studentCursor = studentManager.getAll();
String[] from = new String[] { EventManager.COLUMN_TITLE };
String[] to = new String[] { R.id.title };
cursorAdapter = new SimpleCursorAdapter(this, R.layout.row_events, eventCursor, from, to, 0);

Then, I'd have an AsyncTask subclass which will retrieve data from a RESTful API.

@Override
public void doInBackground() {
    // code to get an array of students

    for(Student student in students) {
        studentManager.save(student);
    }
}

The question would be, in which part would I use the SQLiteCursorLoader and what for

EDIT: The question is more likely to be something like this: I am already implementing my own AsyncTask operation cause I'm retrieving and managing all the data from a server. So, if I am already managing the data in a secondary thread thanks to doInBackground, do I need still SQLiteCursorLoader for any operation?

Was it helpful?

Solution

So, if I am already managing the data in a secondary thread thanks to doInBackground, do I need still SQLiteCursorLoader for any operation?

Probably not. The point of a Loader is to load data asynchronously. If you are doing that yourself, a Loader will not somehow make it more asynchronous. :-)

Just remember that if you change your data, you will need to run a new AsyncTask to update your UI to reflect the changed data, such as by retrieving a fresh Cursor. A CursorLoader does that automatically; a SQLiteCursorLoader only does that "automatically" if you run the database operation through the loader itself.

OTHER TIPS

The purpose of using the CursorLoader interface is so that you're not performing database operations on the main application thread (potentially affecting your application's responsiveness). The SQLiteCursorLoader provides an interface that's similar to the old SimpleCursorAdapter, but will perform database operations in an AsyncTask.

The GitHup page for SQLiteCursorAdapter has more information/background: https://github.com/commonsguy/cwac-loaderex

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top