whoami
whoami

Reputation: 165

Return an int result from 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.

Upvotes: 3

Views: 2448

Answers (3)

CL.
CL.

Reputation: 180080

If name is a string value, you must quote it in SQL. But a better way would be to use a parameter.

To read a single number from a query without having to muck around with a cursor, there is a useful helper function:

int getID(String name) {
    SQLiteDatabase db = getReadableDatabase();
    return (int)DatabaseUtils.longForQuery(db,
            "SELECT IFNULL(MAX(id),0)+1"+
            " FROM "+TableInfo.TABLE_NAME+
            " WHERE appliance=?",
            new String[]{ name });
}

Upvotes: 1

Pratik Butani
Pratik Butani

Reputation: 62419

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.

Upvotes: 3

Dixit Panchal
Dixit Panchal

Reputation: 3436

Try This

public int getMaxID(){
    int maxID = 0;

    String selectQuery = "SELECT "+here you primary key name +" FROM " + TableInfo.TABLE_NAME;
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    if (cursor.moveToFirst()) {
        do{
            maxID = cursor.getInt(0);

        }while(cursor.moveToNext());
    }
    return cursor.getCount();
}

Upvotes: 1

Related Questions