Using a cache to speed up data retrieval from Cursors

Michell Bak
AndroidPub
Published in
3 min readJul 30, 2015

--

It’s easier than you think.

Most Android developers work with Cursors from time to time. It’s most likely not the highlight of the week, but there’s usually no getting around it.

Working with cursors can be a bit tedious and like many other aspects of Android development, users will immediately know if you haven’t done a good job. The most obvious reason for this is slow loading of data — and that affects the user experience. Users want to use apps, not wait for them.

So, what can we do to avoid this? Let’s take a look at an example of how you would usually load some data from a Cursor.

The problem

while (cursor.moveToNext()) {
fooList.add(
new Foo(
cursor.getString(cursor.getColumnIndex("dataColumnName1"),
cursor.getInt(cursor.getColumnIndex("dataColumnName2"),
cursor.getDouble(cursor.getColumnIndex("dataColumnName3")
)
);
}

The code snippet above is a pretty normal example of reading data from a Cursor. You usually need to read data from a number of columns, and this happens over and over again.

So, what can we do about this simple piece of code? Let’s break it down.

--

--