CQM
CQM

Reputation: 44220

Android fetch multiple items from sqlite database

I was like to update (retrieve and possibly edit) multiple items in an SQLite database without using a for/while/dowhile loop

Is this possible using the Cursor? I would like to limit individuals lookups in the table

Is there some complex Android data object that I can dump all results from an SQL query into, that I could then parse for loop

I've heard about Parceable and serializable objects, but that is sort of what I am using the database for.

I currently have methods to call elements by an individual row. And I could put that method in a for loop, or I could have Cursor's query be in a for loop BUT I don't want to do that many accesses.

public String fetchDay(long rowId) throws SQLException {

    Cursor mCursor =

        mapDb.query(true, DAY_TABLE, new String[] {KEY_ROWID, KEY_DAY}, KEY_ROWID + "=" + String.valueOf(rowId), null,
                null, null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    String result = mCursor.getString(mCursor.getColumnIndex(KEY_DAY));
    mCursor.close();
    return result;

}

How would I get all the elements of that table and store in in a complex object without looping

Insight appreciated

Upvotes: 2

Views: 3323

Answers (2)

hovanessyan
hovanessyan

Reputation: 31433

"Is there some complex Android data object that I can dump all results from an SQL query into, that I could then parse for loop?"

Yes, and that's The Cursor. It represents the result set returned by a database query, similar to the JDBC result set. The Cursor should be seen as a container for the results of a database query, although I am not sure if it holds the data itself. If your database query returns multiple rows, you will have them referenced via the cursor. Take a loot at this article to get better idea.

Either way, you have to use some kind of loop to iterate over your cursor for each row of the result set.

Upvotes: 1

Rodrigo Castro
Rodrigo Castro

Reputation: 1583

You can change your query to return more than a single row, by using something like:

KEY_ROWID + " >= " + String.valueOf(firstRowId) + " AND " + KEY_ROWID + " <= " + String.valueOf(lastRowId)

as your where clause.

Doing so, the Cursor will return a range of rows, and you can then iterate on it using a while loop, like this:

mCursor.moveToFirst();  
while (!mCursor.isAfterLast()) {  
    results.add(mCursor.getString(mCursor.getColumnIndex(KEY_DAY)));  
    mCursor.moveToNext();  
}

With results being a List<String>

Note that the while loop used in this solution is way less expensive than querying the table over and over, bexause it iterates on the Cursor object, that's on the memory, instead of making several I/O operations

Upvotes: 2

Related Questions