android - Cursor getString() or getInt() doesn't return the value at given index -
i have created sqlite database , table android app. values can inserted , long id returned no problems. when returned id used retrieve other fields getcolumnindex(column_name) returns correct index, when use getsting , getint value of field, app crashes. android studio doesn't give errors. please help.
database handler class:
public class sqlitedbmanager extends sqliteopenhelper{ private static final int db_version = 1; private static final string db_name = "baby_diary.db" private static final string tbl_babies = "babies"; private static final string babies_baby_id = "baby_id"; private static final string babies_name = "name"; private static final string babies_dob = "dob"; private static final string babies_gender = "gender"; private static final string babies_weight = "weight"; private static final string babies_height = "height"; private static final string babies_theme = "theme"; public sqlitedbmanager(context context, string name, sqlitedatabase.cursorfactory factory, int version, databaseerrorhandler errorhandler) { super(context, db_name, factory, db_version, errorhandler); } public void oncreate(sqlitedatabase db) { string create_tbl_babies = "create table " + tbl_babies + "( " + babies_baby_id + " integer primary key autoincrement, " + babies_name + " text, " + babies_dob + " text, " + babies_gender + " text, " + babies_weight + " real, " + babies_height + " real, " + babies_theme + " text" + " );"; db.execsql(create_tbl_babies); } public babies getbabybyid(long id){ sqlitedatabase db = getwritabledatabase(); string query = "select * " + tbl_babies + " " + babies_baby_id + " = \"" + id + "\";"; cursor cursor = db.query(tbl_babies, null, babies_baby_id + " = " + id, null, null, null, null); if (cursor != null && cursor.getcount() > 0) { //for testing getint int id = cursor.getint(cursor.getcolumnindex(babies_baby_id)); string name = cursor.getstring(cursor.getcolumnindex(babies_name)); cursor.close(); }
you have use cursor.movetofirst() before querying first row cursor. change if statement to:
if (cursor != null && cursor.movetofirst()) {
also, cursor has closed if have no results. i'd recommend writing this:
try { if (cursor != null && cursor.movetofirst) { //for testing getint int id = cursor.getint(cursor.getcolumnindex(babies_baby_id)); string name = cursor.getstring(cursor.getcolumnindex(babies_name)); } } { if(cursor != null) { cursor.close(); } }
this way cursor closed no matter exception may occur.
Comments
Post a Comment