I want to get a specific row by id in android sqlite and have written the following code, but it does not return any records. I have written a getAllRecords()
method which returns all records from database.
Can anyone explain mistake I am making?
public Bank getBankById(int bankId)
{
Cursor cursor=null;
Bank bnk = null;
cursor = this.db.rawQuery("select * from " + BanksTable.NAME + " where " + BanksTable.COL_ID + "=" + bankId , null);
if (cursor != null)
{
if (cursor.moveToFirst())
{
int id = cursor.getInt(cursor.getColumnIndex(BanksTable.COL_ID));
String name = cursor.getString(cursor.getColumnIndex(BanksTable.COL_NAME));
String url = cursor.getString(cursor.getColumnIndex(BanksTable.COL_IMAGE_URL));
byte[] image = cursor.getBlob(cursor.getColumnIndex(BanksTable.COL_IMAGE));
bnk=new Bank();
bnk.setId(id);
bnk.setImageURL(url);
bnk.setName(name);
bnk.setImageByteArray(image);
}
cursor.close();
}
return bnk;
}
I ended up this problem by changing parameter to name. Its weird but I still don't know why it was not working.
I was getting bank id like 0,1,2,3,4 maybe it is not allowed in SQLite or internally affecting it but still I am not sure.
cursor = this.db.rawQuery("select * from " + BanksTable.NAME + " where " + BanksTable.COL_NAME + "='" + bankName + "'" , null);
Here is my approach to get custem object from sqlite db
fun getTaskById(itemId: Int): ModelTask {
val food= ModelTask()
val database = readableDatabase
val kolonlar = arrayOf(DBContract.TaskEntry.COLUMN_T_ID,
DBContract.TaskEntry.COLUMN_T_TITLE,
DBContract.TaskEntry.COLUMN_T_DESC,
DBContract.TaskEntry.COLUMN_T_TIME,
DBContract.TaskEntry.COLUMN_T_PRIORITY,
DBContract.TaskEntry.COLUMN_T_DATE,
DBContract.TaskEntry.COLUMN_T_DONE)
val whereClause = DBContract.TaskEntry.COLUMN_T_ID + " = ? "
val whereArgs = arrayOf(itemId.toString())
val cursor = database.query( DBContract.TaskEntry.TABLE_NAME_TASK, kolonlar, whereClause, whereArgs,
null, null, DBContract.TaskEntry.COLUMN_T_ID + " DESC")
while (cursor.moveToNext()) {
food.id = cursor.getInt(cursor.getColumnIndex(DBContract.TaskEntry.COLUMN_T_ID))
food.title = cursor.getString(cursor.getColumnIndex(DBContract.TaskEntry.COLUMN_T_TITLE))
food.description = cursor.getString(cursor.getColumnIndex(DBContract.TaskEntry.COLUMN_T_DESC))
food.time = cursor.getString(cursor.getColumnIndex(DBContract.TaskEntry.COLUMN_T_TIME))
food.priority = cursor.getString(cursor.getColumnIndex(DBContract.TaskEntry.COLUMN_T_PRIORITY))
food.date = cursor.getString(cursor.getColumnIndex(DBContract.TaskEntry.COLUMN_T_DATE))
food.done = cursor.getInt(cursor.getColumnIndex(DBContract.TaskEntry.COLUMN_T_DONE))
}
database.close()
cursor.close()
return foodList
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With