Android - how to use "select last_insert_rowid();" - android

I'm newbie in Android.
I want to display a new ID in the TextView.
So, I just think of getting latest ID that had been store in the database and declare as Integer add 1 to the value that I get then display to the TextView.
I have read many of the question regarding the getting the latest ID. How can I use select last_insert_rowid();?
Thanks!

last_insert_rowid() works only for records that have been inserted in the same session.
If your column is declared as INTEGER PRIMARY KEY, then SQLite will automatically generate a value for it if you don't specify one in a new record.
If you really need the ID before you have inserted the record, you can execute something like this:
SELECT max(_id) FROM MyTable

if you use autoincrement use
SELECT * from SQLITE_SEQUENCE;
to get the latest id.

Cursor c = database.rawQuery("SELECT last_insert_rowid()", null);
c.moveToFirst();
int id = c.getInt(0);
id += 1;
I'm a newbie too so can't explain very well. The above will get the last insert id from the same session. It won't work if a new session is started, ie you insert something and close the connection and reopen it, as it will then return 0 so you'll need to bear that in mind as your TextView would always show 1. As like you I read many questions about it without knowing how to implement it. The above code is how I managed to use it without getting outofbounds exceptions.

Related

SQLite (Android) : UPDATE query with ORDER BY

Android, SQLite : I want to insert rows in between other rows in myTable using SQLite in android. For this, I am trying to increment ids of the all rows starting say row 3. So that I can insert a new row at position 3.
The primary key of myTable is column id. There are no other constraints in the table.
I have tried using the query mentioned in https://stackoverflow.com/a/9177264/6671004. This query does work in mySQL but not in Android (SQLite)
Here's the line of code :
database.execSQL("UPDATE myTable SET id = (id + 1) where id > 2 ORDER BY id desc");
Here's the error I'm getting on Android Studio (Compile time) :
https://imgur.com/a/9r0iyAa
This is the exception I'm getting if I remove 'ORDER BY id DESC' from the query :
java.lang.RuntimeException: Unable to start activity ComponentInfo{...}: android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: myTable.id (code 1555)
Is this the correct way to do this? Or is there a better way?
As pointed out by many, this is definitely not the correct way to go.
But I found workaround in case someone else is looking for a similar implementation.
Here it is :
UPDATE myTable SET id = - (id + 1) WHERE id > 1;
UPDATE myTable SET id = - id WHERE id < 0;
This is a hack which I found here.
Again, this is not the correct way to go. But just posting a working solution I found.
I have tried using the query mentioned in
https://stackoverflow.com/a/9177264/6671004. This query does work in
mySQL but not in Android (SQLite)
That question is tagged MYSQL. MYSQL has many differences from SQLite.
Here's the line of code :
database.execSQL("UPDATE myTable SET id = (id + 1) where id > 2 ORDER
BY id desc");
The SQLite UPDATE SQL takes the form of :-
i.e. there is no ORDER BY clause and hence the error saying that if you're going to use any KEYWORD then it must be a BETWEEN or IN or a ; (of course you could also extend the condition using AND OR and so on).
This is the exception I'm getting if I remove 'ORDER BY id DESC' from
the query :
The reason being is that the rowid (id being an alias of rowid) has an implied UNIQUE constraint and that the rows will be updated according to the id column in order. So if there are more than 3 rows (or have been and the last row has never been deleted) then when the id is 3, a row with 4 will exist and 3 + 1 = 4 so the row already exists and hence the UNIQUE constraint being encountered.
I want to insert rows in between other rows in myTable using SQLite in
android. For this, I am trying to increment ids of the all rows
starting say row 3. So that I can insert a new row at position 3.
In short that is not a good idea and is virtually definitely not needed.
Is this the correct way to do this? Or is there a better way?
Definitely no
At a guess you want a nice humanly understandable value so you can know what's going on. For example you may present a list with the sequence so you can then say delete the row that has a sequence of 3 and thus equate that to the id column. Fine until you present the list in a different order which may be more user friendly. Suddenly your sequence becomes complicated or even useless and if displayed confusing.
identifiers are intended to identify a row and allow fast access to that row as a numerical index will be more efficient (than a human easily readable non-numeric index) to process. They also cater for reducing unnecessary additional processing (shifting data).
An efficient methodology is presenting the list with tying the id to the position in the list (so position could be the nth element of an array that holds the respective id, regenerating the list (the underlying array) according to a different order so the nth element will still have the respective id).
Embarking on a process of shifting rows will impose additional resource usage for example extra disk IO whose cost is relatively expense. This will be compounded by the fact that you will have to process the rows in reverse order to get around the UNIQUE constraint, that in itself is going to require using even costlier methods because SQLite will by default try to perform the updates efficiently rather than cater for the efficiencies required to digress from recognised/accepted techniques that utilise the underlying efficiencies.
I found this one working. And remove autoincrement from id
String strSQL1 = "UPDATE people_table SET id = (id +1) WHERE id < 0";
String strSQL = "UPDATE people_table SET id = (id -1) WHERE id > 1";
db.execSQL(strSQL);
db.execSQL(strSQL1);

How to get saved id in SugarORM?

SugarORM, in my opinion, is the easiest SQLite library to use and proven to be extremely helpful for junior Android developer like me. SugarORM automatically creates the table and add an AUTO_INCREMENT id column for every java class extending SugarRecord.
Inserting a new row can be as easy as someJavaObject.save(). But how can I get the inserted id once that row is inserted? In PHP I can do something like $id = mysql_insert_id(); after insertion.
I understand that I can just get the id of last row in the table. But the insertion of new row can somehow be very unpredictable. Let's say I have an activity and a service inserting a new row at the same time, I want to avoid getting the wrong id.
Thanks in advance for any help.
The save() method has to return it. Like:
long id = someJavaObject.save()
or try:
someJavaObject.save()
long id = someJavaObject.getId();
As Stan mentioned, save actually returns the id as long value. I used this by today.
If you want to use this for a freshly created row you may do something like this:
Region reg2 = new Region("Graz", 20, 20);
reg1.setId(reg1.save());

Android SQLite Update stops working after calling it two times

I have problems in updating rows in SQLite database in my Android application. It works successfully only, if I update it two times. But when I try to do it on the third time, it doesn't update the same row anymore.
LogCat doesn't show any exceptions. db.update() returns '1'.
I've searched similar issues on StackOverflow and the web. People advic]sed to remove db.close(); from database-helper, because I call it several times, or to use db.update method instead of db.rawQuery() or db.execSQL().
I also tested my query in SQLite client, and it works as it's supposed to.
Here is code of simple database-helper method:
public int updateEventDoneMark(Event event)
{
ContentValues args = new ContentValues();
args.put("completed", event.getCompleted());
return db.update("Event", args, "id" + "='" +event.getId() + "'", null);
}
Is there some SQLite-related issue I should know while I update one database entry several times in a row?
What does your content provider update and URI match look like?
Typical Content providers have a URI for each Table/View for a single row where _id is passed as a where_argument and a URI for multiple rows which uses where and where_arguments to select the rows to be updated.
Also it looks like you update by id. Android really want the id column named "_id", although I don't think is currently your issue, but it really depends on the URI it's using. Content Providers are usually coded with the _id and select by the column for a single row based on _id. That's why I want to see content provider. Your also selecting by the id yourself, this doesn't seem normal, although it could be accomplished, but not the norm. Typically the where part is something like 'colunm name = ?" and the next parameter where_arguments is a string array containing the value to replace the '?'.
Hope this helps.

how would I get a random rowId from my database?

I have a database wherein i get my questions , correct answers/options from... I want my application to automatically generate random rowIds so that the questions could be shuffled.. Of course, the question that's already shown should not display again. I want to get 10 questions then finish();..
Using a random rowId is the wrong approach. What if the database is modified and the ID becomes invalid? You'd have to check every ID and regenerate when an invalid ID comes up.
Instead, you should use a LIMIT clause in your SELECT statement with a random number less than the number of rows in the table.
No need to generate random ids first. Just insert your rows, making sure you have the questionId column.
When you want read your database. Do something like quizid = rand() ....
After that you select the row with quizid in your database
SELECT * FROM quiztable WHERE questionId = quizid
Something like that will give you a random row from your database.
I think you get the point.

Android SQLite delete multiple rows

I want to delete all rows in a table with a specific ID (not primary key).
I have tested two different methods, but they only remove the first row it finds with the specific ID:
db.delete(CalendarTable.TABLE_NAME, "repeat_group="+repeatGroup, null);
and
db.delete(CalendarTable.TABLE_NAME, "repeat_group=?", new String[]{Integer.toString(repeatGroup)});
None of these methods works, how can I remove ALL rows in a table with this specific ID?
Thanks in advance!
UPDATE:
Lol, the method above did work! It was just me the stupid one that called the my own method delete() instead of deleteRepeatGroup(), guess I'm too tired!
Anyways, thank you guys for taking your time.
If everything else fails, you can try the following. Get all rows in the table with the ID you are trying to delete and save the rowID's in an array. Then iterate over the array and delete each row.
I hope this works as expected
you can use
String urQuery = "delete from tablename where Id in ("
+ Id + ")";
here Id may have all ids separated by comma ex. "id1,id2".

Categories

Resources