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());
Related
I am working on Room database and trying to insert list of items(eg. list of Quotes which contains author name and a quote in my case).
Following is the code I am using:
// view model
BaseApp.daoInstance?.appDao()?.insertQuotes(response!!)
// dao
#Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertQuotes(listData: MutableList<Quote>)
When I try to insert the same data again, it always inserts as a new data instead of replacing with the current items.
I have researched a lot for this OnConflictStrategy.REPLACE but could not find any proper answer.
Is there anyone facing the same issue and found solution or am I doing anything wrong?
Thank you in advance...!!!
Room, will not check and compare if you have the quote already in the DB.
What it will do is look if the primary key already exists in the DB if it does, Room will replace all old data with the new one.
In your case, you are not specifying an ID so the DB is generating a unique one for you.
What you should do is create a Query that will search for this quote in the DB something like this:
#Query("SELECT * from quote_table WHERE author = :author AND quote = :quote")
List<Quote> getQuoteByAuthorAndQuote(string author, string quote);
This should return a list with a single quote if one is found and empty if it does not exist.
If you would like to override the old one just update the data in the Quote POJO and insert it to the DB using Room.
Have you tried to index your main column and mark it as unique?
#Index(value = {"quote"}, unique = true)}
It suppose to search for your unique or primary key and compare then replace, while in your case you're not defining an ID so it will generate a unique one for you, so it won't even compare and will consider any item as a new one.
Write a new query and function to solve this issue.
When I had same problem, changes in imports did the trick, added following import:
import androidx.room.*;
I have 4 EditTexts in dataBase
I delete the second one
The database is numbered 1,3,4
I now want it to be renumbered as 1,2,3.
I looked at many solutions
But I could not find a complete answer..
I do not know what should be in writing
I tried the following code .
But it did not happen
db.delete("SQLITE_SEQUENCE","NAME = ?",new String[]{TABLE_NAME});
Does anyone have the full answer ?
In general, this is poor design for a database. An ID should be consistent for a piece of data, regardless of its peers--it should not fluctuate just because another row was deleted.
That being said, you could always use an UPDATE statement to SET ID = ID-1 WHERE ID > (the ID of the row you deleted). This would work. I don't recommend this approach, but you can.
You can recover this space by executing the SQLite VACUUM command.
Call db.execSQL("VACUUM") after delete
I'm using Ormlite for database operations on my Android App.
In one of the methods, I need to delete the last row in a table. However I m not able to find out how. I'm successfully deleting rows when giving an argument, but in this specific case I don't have arguments.
Here's my attempt:
LottoDatabaseHelper helper = OpenHelperManager.getHelper(getApplicationContext(), DatabaseHelper.class);
//You get helper
Dao dao = helper.getDao(MyTable.class);
//get your Dao
DeleteBuilder<MyTable, Integer> deleteBuilder = dao.deleteBuilder();
//How can I specify last row here?
deleteBuilder.delete();
Thank you for your help
I haven't used Ormlite .. here is a simple solution which can use with any database ... As you said you can delete a row by passing argument...
try this..
1. Find the last id using the query..
eg. SELECT id FROM table_name ORDER BY id DESC LIMIT 1
// will return the last row id
2. then pass the id as a parameter to delete ...
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.
I write app on android which will use android SQLite database. I have table which will contain data rows with unique Id. From time to time I need to add new row or update old row. For now I when I want to add/update data I must check if I have row with specified Id in table. If I have I update suitable row. If I dont I create new row with new unique key. My question is: is there something in Android what can automagically check if in database is row with specified id and then just update it and if there isnt such row add new?
Check out the SQLite documentation for the insert statement. You can use a insert or replace statement (or just replace, which is a shortcut).
You use it just like you would a traditional insert statement. This is probably useful in your case since you already have the key known.