0

Below is a code snippet from an Android tutorial book I was following. loadInBackground gets a cursor and then does cursor.getCount() to "ensure that the content window is filled". What does this mean? The docs on getCount just say "returns number of rows in the cursor". I've Googled for this "ensure that the content window is filled" and there are quite a few snippets that do this, all with the same comment, but no explanation of why this is needed/how it works.

import android.content.AsyncTaskLoader;
import android.content.Context;
import android.database.Cursor;

public abstract class SQLiteCursorLoader extends AsyncTaskLoader<Cursor> {

    private Cursor cursor;

    public SQLiteCursorLoader(Context context) {
        super(context);
    }

    protected abstract Cursor loadCursor();

    @Override
    public Cursor loadInBackground() {
        Cursor cursor = loadCursor();
        if (cursor != null) {
            cursor.getCount(); // ensure that the content window is filled
        }
        return cursor;
    }

}
Tan Wang
  • 811
  • 1
  • 6
  • 16

1 Answers1

2

As you know, Database returns a Cursor after a query. However, Cursor is only effectively filled with data when you try to read some information like: cursor.getCount() or cursor.moveToFirst() etc...

This is more evident during large queries.

For example, imagine that query below would return thousand of results:

Cursor cursor = db.rawQuery("select * from TABLE", null);

That statement however, does not take too much time to run...

However, when you finally call cursor.getCount() or cursor.moveToFirst(), for the first time, you may see some "lag" since the cursor is being effectively being filled with the data from database.

If you do that in Main UI Thread, you app may freeze for some seconds. Specially on low tier devices.

So, by calling that method, I believe that author is trying to ensure that data was fully loaded during loadInBackground(). This way, he ensure that data is loaded in Background an not in any other future method. This way, any future call to getCount() or moveToFirst() will be executed very quickly since the data was already loaded.

Anyway, it is not mandatory..

guipivoto
  • 18,327
  • 9
  • 60
  • 75