Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Strings from A Cursor in Android?

My cose is SIMPLE. I have a SQLite-Database with three columns:

  1. rowid
  2. title => text
  3. content => text

This is a method in my dataBase-class:

public Cursor fetchMessage(String tableNane, int id) {
    return myDataBase.rawQuery("SELECT rowid as _id, title FROM "+tableName
    +" WHERE rowid = "+id, null);
}

This method will return only one row.

In my activity I wrote this:

Cursor cursor = myDbHelper.fetchMessage(tableName, id);

Now, I want to store the content field's text in a String.

How can this be done?

like image 659
iTurki Avatar asked Jul 10 '11 11:07

iTurki


People also ask

Which method is used to get data from cursor?

Once the cursor's position is pointing to a valid row, the columns of the row can be read from the cursor. To read the data, the code in Listing 5.10 uses two methods from the cursor class: Cursor. getColumnIndexOrThrow() and one of the type get() methods from the Cursor class.

What does cursor moveToFirst do?

Calling moveToFirst() does two things: It allows us to test whether the query returned an empty set (by testing the return value) It moves the cursor to the first result (when the set is not empty)

What is cursor getColumnIndex?

getColumnIndex(String columnName) Returns the zero-based index for the given column name, or -1 if the column doesn't exist. abstract int. getColumnIndexOrThrow(String columnName) Returns the zero-based index for the given column name, or throws IllegalArgumentException if the column doesn't exist.

What is the use of cursor in Android?

A Cursor represents the result of a query and basically points to one row of the query result. This way Android can buffer the query results efficiently; as it does not have to load all data into memory.


1 Answers

Use this:

if (cursor.moveToFirst()) {
    str = cursor.getString(cursor.getColumnIndex("content"));
}
like image 64
CeKup Avatar answered Oct 05 '22 05:10

CeKup