how to fetch a row using id sqlite?
28,691
Solution 1
1- or better to use parametrized statement
String query = "SELECT COUNT(*) FROM " + tableName + " WHERE columnName = ?";
cursor = db.rawQuery(query, new String[] {comment});
2 - use if with conditon c.moveToFirst() or c.getCount() >0 or (!c.isAfterLast())
if (c.moveToFirst()){
do{
//if you not need the loop you can remove that
id = c.getInt(c.getColumnIndex("_id"));
}
while(cursor.moveToNext());
}c.close();
Solution 2
Is the id column title actually "ID"? Or is that a variable that is set to "_id" (the usual column name for the primary key in an Android database)?
If the latter, your query is not right, because you are using "ID" as the literal column name. Try changing it to this:
Cursor cursorc = db.rawQuery("SELECT * FROM LIST WHERE " + ID + " = " + id, null);
or even this:
Cursor cursorc = db.rawQuery("SELECT * FROM LIST WHERE _id = " + id, null);
Solution 3
try using
Cursor cursorc = db.rawQuery("select * from list where ID = ?", new String[] {id+""});
Solution 4
try with this way
Suppose long id=5;
String[] col=new String[]{KEY_ROWID,KEY_NAME,KEY_ADDRESS}; // your column which data u want to retrive if id is same
Cursor c=db.query(DATABASE_TABLE, col, KEY_ROWID+"="+id,null, null, null, null);
if(c!=null){
c.moveToFirst();
// get data here which u want accroding to ur requirement
}
Author by
Adarsh H S
Java | Python | Open Source Software compliance & Governance Expert | Storyteller | Technical Trainer
Updated on February 21, 2020Comments
-
Adarsh H S about 4 years
This is a simple one! yet, I am missing something. Please help me out. Here, I am trying to fetch values by id, but not able to do so. It is returning same values even after changing id's value.
db = openOrCreateDatabase("DBSOURCE", 0, null); Cursor cursorc = db.rawQuery("SELECT * FROM LIST WHERE ID="+id+"", null); cursorc.moveToFirst(); int NameID = cursorc.getColumnIndex("Name"); int mobilenumberID = cursorc.getColumnIndex("MoblieNumber"); edName.setText(cursorc.getString(NameID)); edMobNum.setText(cursorc.getString(mobilenumberID)); cursorc.close(); db.close();
-
Khan almost 12 yearshave make changes accroding to ur column name supposue ur column name=_in than String KEY_ROWID="_id" same as for database_table and other fields