0

I have created a database that holds names, info and also gives an "_id" for each object that gets save to the database.

now i want with the next function to get at the end the id that the new added object is getting - i have tried the next code - but im sure it's not the right way

public long insertAuto(Student student){
        SQLiteDatabase db = dbOpen.getWritableDatabase();

        ContentValues vals = new ContentValues();
        vals.put(Constants.STUDENT_NAME, student.getName());
        vals.put(Constants.STUDENT_INFO, movie.getInfo());

        db.insert(Constants.TABLE_NAME_STUDENTS, null, vals);

            //this is where i thinks is my mistake! 
        long id = student.getId();

        db.close();

        return  id;
    }

so thank you for any kind of help

4this
  • 759
  • 4
  • 13
  • 27
  • 1
    I think this question already exist. check it from: http://stackoverflow.com/questions/4017903/get-last-inserted-value-from-sqlite-database-android – blitzen12 Nov 04 '13 at 08:29

5 Answers5

3

Check the documentation of SQLiteDatabase.insert()

It returns the newly inserted rowId for you.

public long insertAuto(Student student){
    SQLiteDatabase db = dbOpen.getWritableDatabase();

    ContentValues vals = new ContentValues();
    vals.put(Constants.STUDENT_NAME, student.getName());
    vals.put(Constants.STUDENT_INFO, movie.getInfo());

    long id = db.insert(Constants.TABLE_NAME_STUDENTS, null, vals);

    db.close();

    return  id;
}
bakriOnFire
  • 2,685
  • 1
  • 15
  • 27
2

Use the return value of SQLiteDatabase.insert() method.

As the documentation states, this method returns

the row ID of the newly inserted row, or -1 if an error occurred 
Ahmad Y. Saleh
  • 3,309
  • 7
  • 32
  • 43
0

You can try this :

 String query = "SELECT ROWID from TABLE_NAME_STUDENTS order by ROWID DESC limit 1";

 Cursor c = db.rawQuery(query);

 if (c != null ) {

     c.moveToFirst();
     id = c.getLong(0);
 }
David N
  • 509
  • 4
  • 12
0

1/ If you generate id in the application yourself, then what you're doing is correct.

lastId = theLastSavedStudentObject.get(id);

2/ Look at your code, it seems you let the database generates the id automatically (MySQL autoincrement perhaps), then the last id must be select from database or by return from the insert function.

lastSaveId = db.insert(Constants.TABLE_NAME_STUDENTS, null, vals);

OR query directly from DB using this SQL query:

select max(id) from mytable;   (for autoincrement ID)
0

Whenever you run a query for insertion on database, it returns the row id of the currently inserted row as long value.

long id = db.insert(Constants.TABLE_NAME_STUDENTS, null, vals);
return id;

This row id will be unique and can be used in further queries.

Bette Devine
  • 1,196
  • 1
  • 9
  • 23