Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching a single value from SQLite

This method is in databasehelperclass returning single value expected

  public Cursor getUserDataFromDb(){
    SQLiteDatabase sqLiteDatabase=this.getWritableDatabase();
    Cursor rawdata=sqLiteDatabase.rawQuery("SELECT NAME FROM " +TABLE_NAME+" ORDER BY ID DESC LIMIT 1)",null);
    return rawdata;

}

fetching value from usertable inside an Activity

    try {
        Cursor cursor = mydb.getUserDataFromDb();
        if (cursor.moveToFirst()){
           name_resultfromdb = cursor.getString(0);
        }
        else {
            Toast.makeText(this,"Setup your Account",Toast.LENGTH_LONG).show();
        }

    }catch (Exception e){
        e.printStackTrace();
    }

I am using the above code to get the data, but I am getting null.
I want to show this value into a TextView, but I am unable to get it.

like image 261
brijesh kumar Avatar asked Dec 03 '25 16:12

brijesh kumar


1 Answers

There is a helper function to read a single value:

String result = DatebaseUtils.stringForQuery(db,
            "SELECT NAME FROM "+TABLE_NAME+" ORDER BY ID DESC LIMIT 1", null);

Anyway, if this query does not return a value, then the table is empty, or the value in the Name column of the last record is empty.

like image 165
CL. Avatar answered Dec 06 '25 08:12

CL.



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!