user1265623
user1265623

Reputation: 95

How can i fetch the last value inserted into sqlite Database

I have a doubt to be clarified. How can i fetch the last value inserted into sqlite DB. I need code for that.I tried using query like this:

SELECT uname,umessage,utime FROM chatmessage ORDER BY utime DESC limit 1;

Where am i doing wrong?? I need help in this issue.

Thanks in advance.

Upvotes: 1

Views: 950

Answers (2)

Avi Kumar
Avi Kumar

Reputation: 4433

if the value is last its id should be maximum

you can fire the query like this

c = db.rawQuery("SELECT uname,umessage,utime FROM tablename WHERE " +
                "Id = (SELECT MAX(Id) FROM tablename ); ",null);

for last message by particular user add user id column in the message table like

id | userid | message | utime


1  |   1    | wlhf    | 3:10

2  |   3    | dfhhfjh | 2:15

3  |   1    | kjfedhr | 4:00

4  |   2    | hejhe   | 1:15

5  |   3    |  kegekr | 3:30

6  |   1    | wlhf    | 3:10

7  |   3    | dfhhfjh | 2:15

8  |   1    | kjfedhr | 4:00

9  |   2    | hejhe   | 1:15

10  |   3    |  kegekr | 3:30




c = db.rawQuery("
select message  from table1 where 


userid  = 1 ; ",null);




recieve like



ArrayList<String> listMessg = new ArrayList<String>();



cursor = dbm.columnValueofCourse();
        cursor.moveToFirst();
        startManagingCursor(cursor);

for (int i = 0; i < cursor.getCount(); i++) {

    reciv = cursor.getString(cursor
                    .getColumnIndex("message"));
listMessg.add(reciv_Par);
}

int sizeoflist = listMessg.size();

because in ascending order , the last index 
of array list will be the last message of the user

System.out.println("THE LAST MESSAGE BY USER IS  " + listMessg.et(sizeoflist -1));

Upvotes: 0

Vyacheslav Shylkin
Vyacheslav Shylkin

Reputation: 9801

SQLiteDatabase returns id of inserted row. You can rememember this id in some value and use it.

long lastId = db.insert(......);

Upvotes: 1

Related Questions