Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return an int result from SQLite

Tags:

android

sqlite

So I want to find the max ID and return it by adding 1.

The following is my code in SQLhelper. It looks so wrong because its public void in but i returned CR. Im a little bit confused since cursor is used to read records, but i only want the result of integer to be returned using the SQL query.

 public int getID( String name){
    String idquery="SELECT IFNULL(MAX(id),0)+1 FROM "+TableInfo.TABLE_NAME+ " WHERE appliance="+name;
    SQLiteDatabase SQ=this.getReadableDatabase();
    Cursor CR=SQ.rawQuery(idquery,null);
    return CR;
}

This is how i call it from another activity

int no_id=DB.getID(name);

Someone please help me. Thank you.

like image 822
whoami Avatar asked May 11 '26 13:05

whoami


1 Answers

You have to do like:

public int getID( String name){

    String idquery="SELECT IFNULL(MAX(id),0)+1 FROM "+TableInfo.TABLE_NAME+ " WHERE appliance="+name;

    SQLiteDatabase SQ=this.getReadableDatabase();
    Cursor CR=SQ.rawQuery(idquery,null);


     int id = -1;

     if (CR != null && CR.getCount() > 0) {
         CR.moveToFirst();
         id = CR.getInt(c.getColumnIndex(YOUR_COLUMN_NAME));
         CR.close();
     }
     return id;
}

Edited:

Change your column alias in query IFNULL(MAX(id),0)+1 like IFNULL(MAX(id),0)+1 as maxcount then you can give it while taking value from cursor:

id = CR.getInt(c.getColumnIndex("maxcount"));

and it will return Integer as you want.

Hope it will helps you.

like image 182
Pratik Butani Avatar answered May 13 '26 04:05

Pratik Butani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!