How to Check If Data Is Inserted in Room Database

How to check if data is inserted in Room Database

The problem was in the thread.
Room doesn't allow you to run database queries in main thread. The call to insert method was inside of a try-catch block, and I was ignoring the exception.
I fixed it, and here's how it reads right now.

doAsync {
val addedID = appContext.db.rallyDAO().addVehicleListItem(vehicle)
Logger.d("vehicle_lsit_item","Inserted ID $addedID")
}

Also, I reviewed the documentation, the insert method may return a Long (or List of Long in case of List passed to insert). I also changed the signature of insert, and here is the modified code

@Insert(onConflict = OnConflictStrategy.REPLACE)
fun addVehicleListItem(vehicleListItem:VehicleListItem):Long

P.S. I am using anko for doAsync

Check if row is inserted into Room database

According to the Docs here Room Dao @Insert

If the @Insert method receives only 1 parameter, it can return a long, which is the new rowId for the inserted item. If the parameter is an array or a collection, it should return long[] or List instead.

The bottom line is,
A method annotated with the @Insert annotation can return:

  1. a long value for a single insert operation.
  2. a long[] or Long[] or List for multiple insert operations.
  3. void if you don't care about the inserted id(s).

If the return value is -1 or negative consider the operation is failed according to docs.

Edit Answering @patrick.elmquist comment

From Room Generated Code. EntityInsertionAdapter and SupportSQLiteStatement

/**
* Execute this SQL statement and return the ID of the row inserted due to this call.
* The SQL statement should be an INSERT for this to be a useful call.
*
* @return the row ID of the last row inserted, if this insert is successful. -1 otherwise.
*
* @throws android.database.SQLException If the SQL string is invalid for
* some reason
*/
long executeInsert();

How do I check if there's a certain item in database when using Room in Android?

I would do it by making another query that returns true if the item exists or false if it doesn't.

@Query("SELECT EXISTS (SELECT 1 FROM example_table WHERE id = :id)")
fun exists(id: Int): Boolean

And call it like this so you don't need to check if it's null or not:

val exists = dao.exists(id)

How can I check whether data exist in Room database before inserting into database on Android?

Update your query with this annotation :

@Insert(onConflict = OnConflictStrategy.REPLACE)

How can I know @Insert of Room is completed?

If the method call succeeded for insert, then it was succesful, otherwise you'd get an exception.

Also, these don't have to be void-returning methods.

You can have @Insert return the type of the primary key in the table, which will be the key of the newly inserted record.

@Insert(onConflict = OnConflictStrategy.IGNORE)
fun saveProfile(model: Profile): Int

In case of @Delete, it will return the number of rows deleted if you return an Int:

@Delete
fun deleteProfiles(profiles: List<Profile>): Int

Same goes for a more manual implementation using @Query, returns the number of rows affected if you return an Int:

@Query("DELETE FROM profiles")
fun deleteAllProfiles(): Int

Check if object is exists in room database android java

You need to observe the value which you get from your checkArticle method.
Use MutableLiveData in the following way:

public class SavedArticlesRepository {

....

LiveData<Integer> checkItem(Article article) {
MutableLiveData<Integer> data = MutableLiveData();
SavedNewsRoomDatabase.databaseWriterExecutor.execute(() -> {
int count = savedNewsDAO.checkArticle(article.title, article.content, article.description);
data.postValue(count);
});
return data;
}

}

Now in your viewmodel, also extend the checkArticle with LiveData

public LiveData<Integer> checkArticle(Article article) {
return savedArticlesRepository.checkItem(article);
}

In your fragment or activity observe this method:

 saveArticleButton.setOnClickListener(v -> {
Article article = new Article();
article.title = intent.getStringExtra("title");
article.description = intent.getStringExtra("description");
article.content = intent.getStringExtra("content");
article.urlToImage = intent.getStringExtra("image");

savedNewsViewModel.checkArticle.observe(getViewLifeCycleOwner(), new Observer{ count ->
if(count > 0){
Toast.makeText(this, "Article already exists", Toast.LENGTH_SHORT).show();
} else {
savedNewsViewModel.insert(article);
Toast.makeText(this, "Article saved successfully", Toast.LENGTH_SHORT).show();
}
});

});

I haven't tested this code, as I don't work with Java anymore. But should work fine.
If I can suggest, I'd say learn Kotlin and coroutines. This stuff is so much easier when you're using Kotlin and coroutines.

Leave a comment if you need any more help with this.



Related Topics



Leave a reply



Submit