Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing value from SELECT to a variable

Tags:

android

mysql

I was making an Android applicaton, which has table called maintable in database.

At first when the user installs my app it will create a row in the table for user which has _id as primary key. And I user query similar to this:

INSERT INTO table_name (col1, col2,...) 
VALUES ('val1', 'val2'...);

SELECT LAST_INSERT_ID();

By this I get the primary key for sure, but I want to store this value of users primary key into a variable in my application so that I can refer to users information using that value in the variable.

Any help offered will be appreciated. Please...

like image 927
user3781907 Avatar asked Jun 01 '26 10:06

user3781907


1 Answers

To retrieve the last inserted id, you could do something like:

public int getLastInsertedId(){

        String query = "SELECT id FROM my_table ORDER BY id DESC LIMIT 1";
        Cursor c = db.rawQuery(query, null);
        int lastInsertedId = 0;
        while(c.moveToNext()){

            lastInsertedId = c.getInt(0);

        }
        c.close();

       return lastInsertedId;

    }

You can then save that into a variable such as:

int myId = getLastInsertedId();

If you want to save that ID for later use, you can save it inside SharedPreferences

public void saveId(int id){
    SharedPreferences sp = getSharedPreferences("SP_ID", MODE_PRIVATE);
    Editor editor = sp.edit();
    editor.putInt("SAVED_ID", id);
    editor.commit();
}

public int getSavedId(){

    SharedPreferences sp = getSharedPreferences("SP_ID", MODE_PRIVATE);
    return sp.getInt("SAVED_ID", 0);

}

Then you can retrieve it like:

int storedId = getSavedId();
like image 78
Azae B. Garcia Avatar answered Jun 02 '26 22:06

Azae B. Garcia



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!