Android Sqlite Select Query
Solution 1:
Try trimming the string to make sure there is no extra white space:
Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);
Also use c.moveToFirst()
like @thinksteep mentioned.
Solution 2:
This is a complete code for select statements.
SQLiteDatabasedb=this.getReadableDatabase();
Cursorc= db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
do {
// Passing values Stringcolumn1= c.getString(0);
Stringcolumn2= c.getString(1);
Stringcolumn3= c.getString(2);
// Do something Here with values
} while(c.moveToNext());
}
c.close();
db.close();
Solution 3:
Try using the following statement:
Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE name = ?", new String[] {name});
Android requires that WHERE clauses compare to a ?, and you then specify an equal number of ? in the second parameter of the query (where you currently have null).
And as Nambari mentioned, you should use c.moveToFirst()
rather than c.moveToNext()
Also, could there be quotations in name? That could screw things up as well.
Solution 4:
Here is the below code.
String areaTyp = "SELECT " +AREA_TYPE + " FROM "
+ AREA_TYPE_TABLE + " where `" + TYPE + "`="
+ id;
where id is the condition on which result will be displayed.
Solution 5:
public User searchUser(String name) {
Useru=newUser();
SQLiteDatabasedb=this.getWritableDatabase(); //get the database that was created in this instanceCursorc= db.rawQuery("select * from " + TABLE_NAME_User+" where username =?", newString[]{name});
if (c.moveToLast()) {
u.setUsername(c.getString(1));
u.setEmail(c.getString(1));
u.setImgUrl(c.getString(2));
u.setScoreEng(c.getString(3));
u.setScoreFr(c.getString(4));
u.setScoreSpan(c.getString(5));
u.setScoreGer(c.getString(6));
u.setLevelFr(c.getString(7));
u.setLevelEng(c.getString(8));
u.setLevelSpan(c.getString(9));
u.setLevelGer(c.getString(10));
return u;
}else {
Log.e("error not found", "user can't be found or database empty");
return u;
}
}
this is my code to select one user and one only so you initiate an empty object of your class then you call your writable Database use a cursor in case there many and you need one here you have a choice Use : 1-
if (c.moveToLast()) { } //it return the last element in that cursor
or Use : 2-
if(c.moveToFirst()) { } //return the first object in the cursor
and don't forget in case the database is empty you'll have to deal with that in my case i just return an empty object
Good Luck
Post a Comment for "Android Sqlite Select Query"