how to pull a single row from android cursor containing several rows

I m fetching data from a table in SQLite.

This is my code

String[] sColoumns = { "_id", "userloginid", "password", "firstname", "lastname", "email", "address"};
Cursor cursor = db.query("users", sColoumns, null,null,null,null,null); 

The query returns all rows of the table in the cursor.

Now i want to pull the rows one by one from the cursor or load them into a data table and then pull them one by one(like in visual studio).

Is there anything available or anything i can do to achieve this?

thanks in advance.

Upvotes: 0

Views: 4887

Answers (1)

andyandy
andyandy

Reputation: 928

There are two ways to answer your question.

1) You can simply iterate over the cursor and do whatever you want with the row data:

String[] sColoumns = { "_id", "userloginid", "password", "firstname", "lastname", "email", "address"};
Cursor cursor = db.query("users", sColoumns, null,null,null,null,null); 

try {
    int firstNameColIndex = cursor.getColumnIndex("firstname");
    int lastNameColIndex = cursor.getColumnIndex("lastname");

    while (cursor.moveToNext()) {
        String fullName = cursor.getString(firstNameColIndex) + cursor.getString(lastNameColIndex);
    }
} finally {
    cursor.close();
}

2) A common use case is to display data in a list view. Since Android 3.0 Honeycomb (and the Android Support/Compatiblity lib for earlier versions) the best practice is to use a Loader for taking care of managing the cursor. For example it will take care of updating the list view if data is updated in a content provider. I recommend reading http://developer.android.com/guide/topics/fundamentals/loaders.html (see links to samples at the bottom) to understand this topic.

Upvotes: 2

Related Questions