Delete last row using Ormlite - android

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 ...

Related

Room database onConflict = OnConflictStrategy.REPLACE not working

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.*;

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());

Validate for empty row in Android

I have a table in which 5 rows are there. But I have to feed the value of row in the database in which values are filled. It can be 2nd, 3rd or all. So how would I find out and validate the same. The rows are not generating dynamically. The rows are already in layout with some ids. I know it's weird but requirement is this only. Please suggest me how can I do this.
For that you have some alternative,
I think you should insert default record into the field so that will be easy instead of validating, if you think that is good.
When get the result from the DB just put the single condition
String name = Db.get_name().toString();
if(name!=null)
{
Row_TextView.setText(name);
}
else
{
Row_TextView.setText("-"); // or what ever you want to set
}
- Here is database example
Try it i hope it works for you
What you need is a Cursor to read data from the db
Then loop through the fetched data (if 'getCount()>0' then while(!cursor.isAfterLast))
For each row check if the data is present in specific columns in your db and if not then do insert it in the db

Imported sqlite database is missing data and mixing columns

I have put an sqlite database in my assets folder and imported it onto the phone.
I created an object with multiple properties and when I create a list of that object and assign each property a value from a column of the table they get mixed up
Below is my code
public ArrayList<Exercise> getExercisesFromQuery(String Query) {
ArrayList<Exercise> ExerciseList = new ArrayList<Exercise>();
Cursor cursor = mDb.rawQuery(Query, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Exercise e = new Exercise();
e.setID(Integer.parseInt(cursor.getString(0)));
e.setName(cursor.getString(1));
e.setMuscle(cursor.getString(2));
e.setDescription(cursor.getString(3));
e.setFilepath(cursor.getString(4));
e.setSets(cursor.getString(5));
e.setReps(cursor.getString(6));
e.setEquipment(cursor.getString(7));
e.setPrimaryMuscle(cursor.getString(8));
e.setSecondaryMuscle(cursor.getString(9));
e.setDifficulty(cursor.getString(10));
// Adding contact to list
ExerciseList.add(e);
} while (cursor.moveToNext());
}
return ExerciseList;
}
The current problem is when I do object.getName it gives me the muscle and if I do object.getmuscle it is blank and there is no value but if I do object.getDescription it works fine.
It is not a problem with the database it works fine in any sqlite manager.
Any ideas as to what is wrong?
The reason why the columns are not being returned in the order you expect is not clear. They should come back in the order specified in your query or in the order they are on the table if you are doing SELECT *. However it is not really necessary to address that specific puzzle.
A more defensive and maintainable coding approach is to request each column's index from the cursor by using the getColumnIndexOrThrow method instead of hardcoding them. For example:
int ID_INDEX = cursor.getColumnIndexOrThrow("_id");
int NAME_INDEX = cursor.getColumnIndexOrThrow("name");
If the column doesn't exist you'll get an exception. If it does, you now have its index within the cursor which you can use in the calls to cursor.getString:
e.setID(Integer.parseInt(cursor.getString(ID_INDEX)));
e.setName(cursor.getString(NAME_INDEX));
So you no longer need to worry about what order the columns come back in and you won't need to change any hardcoded index values if your query changes in the future.
Make sure that the columns in the database are in the correct order - column Name should be the second column, column Muscle should be the third column.

Get newly added row in SQLite table

In my android application, I have a SQLite database containing a table with an id column with AUTOINCREMENT. I'm using an INSERT statement to add a new row but I need to immediately access this row so I can refer to it by the ID. So does anyone know of a way to get the ID of this newly added row?
Thanks!
SQLiteDatabase.insert returns the id of the newly created row.
So, you would get the row like so:
long row = mDatabase.insert(MY_TABLE, "id", values);
(above of course is just an example)
See here: SQliteDatabase.insert
Returns
the row ID of the newly inserted row, or -1 if an error occurred
I think you can use last_insert_rowid() function
From documentation
The last_insert_rowid() function returns the ROWID of the last row insert from the database connection which invoked the function. The last_insert_rowid() SQL function is a wrapper around the sqlite3_last_insert_rowid() C/C++ interface function.
Try this out:
select id from myTable where id = (select max(id) from myTable);
When you insert a row, the long value which is return is the id of inserted row : see
public long insert (String table, String nullColumnHack, ContentValues values)
Copy past link :
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#insert(java.lang.String, java.lang.String, android.content.ContentValues)

Categories

Resources