I am trying to get information from my database and put it into a string to print it on screen. i thought i could use the code below to do it but it gives out some information about the cursor instead of the information inside the cursor.
datasource = new DataBaseHelper(this);
datasource.open();
Cursor c = datasource.getAllGoals();
startManagingCursor(c);
String g = c.toString();
goal.setText(g);
datasource.close();
The cursor can be thought of as a pointer to some underlying data. Running c.toString()
on the cursor object would print the default Cursor
class' implementation of its string representation (an at-sign character @
and the unsigned hexadecimal representation of the hash code of the object) which is not what you want.
To retrieve underlying database data, you will need to call c.getString(columnIndex)
(source), or whatever column datatype you require for that particular column index.
Here's an example modified from source:
Say you have created a table
private static final String DATABASE_CREATE =
"create table comments ( "
+ "_id integer primary key autoincrement, "
+ "comment text not null);";
and your getAllGoals
function returns a cursor which points to data about both _id
and comment
. Now you only want to show the details about the comment
column. So you have to run c.getString(1)
. Suppose your getAllGoals
function returns a cursor which only points to data about the comment
column. Now you have to run c.getString(0)
.
I would recommend that you download the source code in the provided example and go through how data is retrieved from a cursor.
EDIT:
public List<Comment> getAllComments() {
List<Comment> comments = new ArrayList<Comment>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_COMMENTS,
allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {//retrieve data from multiple rows
Comment comment = cursorToComment(cursor);
comments.add(comment);
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return comments;
}
private Comment cursorToComment(Cursor cursor) {
Comment comment = new Comment();
comment.setId(cursor.getLong(0));
comment.setComment(cursor.getString(1));
return comment;
}
source
openDataBase();
Cursor c = myDataBase.rawQuery("SELECT * FROM tb_aa_City where City_Name = '"+cityname+"'", null);
if (c.getCount() > 0) {
c.moveToFirst();
seqid = c.getString(4);
System.out.println("In DB..getSequenceID..."+seqid);
}
c.close();
myDataBase.close();
SQLiteDatabase.releaseMemory();