Storing a value from a SELECT into a variable

I was making an android app where the table was called maintable in the database.

First, when a user installs my application, it will create a row in the table for the user that has _id as primary key. And the custom query is similar to this:

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

SELECT LAST_INSERT_ID();

      

To this I will get the primary key, but I want to store that user's primary key value in a variable in my application so that I can reference the users information using that value in the variable.

Any help offered would be greatly appreciated. You are welcome,...

+3


source to share


1 answer


To get the last inserted ID, you can 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;

    }

      

Then you can store this in a variable, for example:

int myId = getLastInsertedId();

      



If you want to keep this ID for later use, you can store 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 get it like:

int storedId = getSavedId();

      

+1


source







All Articles