cant find out how to read a row from room database - android

I am new to Android studio, especially in room database.
I can't find out how to read a row from room database
//in dao
#Query("SELECT * from qarindosh_table LIMIT 1")
Qarindosh getAnyQarindosh();
I couldn't find out how to read a row. Please help.
Room database is working.

This is how you do it
#Query("SELECT * FROM qarindosh_table")
List<ModelClass> getAllItems();

If I understand you correctly, you wish to read 1 specific row from a database. In order to do that, you need to query by primary key, usually named id in the Entity. Something like that:
#Query("SELECT * FROM qarindosh_table WHERE id=(:id)")
Qarindosh loadQarindoshById(int id);

Related

Storing JSON data from the assets into the DB with Room

I have a big JSON file in the assets and I want to store it in the DB using Room.
Right now, my app takes the JSON file and parses it, generating some data models containing the information.
What is the way to insert it into the DB? Is the repository the one to do that? How do I know if the database is empty or that all that info has already been dumped into the DB?
Thanks in advance!
What is the way to insert it into the DB? Using an Insert query in your entity DAO, like:
#Insert
fun insertTickets(vararg tickets: Ticket)
Is the repository the one to do that? This is a matter of structure or your application. If you have a repository, then yes, the repository should be the one speaking with the database.
How do I know if the database is empty or that all that info has already been dumped into the DB? To know if the database is empty you would have to query all tables for data, either by issuing a Query with COUNT(*), like
#Query("SELECT COUNT(*) FROM X")
fun numberOfRecordsInX(): Long
or asking for any one row to see if something is returned. No idea which can be faster:
#Query("SELECT * FROM x ORDER BY rowid LIMIT 1")
fun gimmeAnyRowInX() : EntityX

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 do search in Room data base?

I have created a room database, and showed my data in a RecyclerView. I know how to add, delete, deleteAll, update data in room data base, but the problem is I don't know how to perform search in room data base?
I have added a search view in the tool bar. But I don't know how to add Queries in NoteDao and the remaining classes, e.g. in my adpter, MainActivity etc.
If you're able to show your Room database in the RecyclerView, this would mean you should know how to use the #Query() tag for fetching your data.
Searching is done using the same #Query tag using the WHERE keyword.
For example, if you wish to find a specific note:
#Query("SELECT * FROM notes WHERE id == :id")
public Note getNote(String id)
However, that's just the simplest way to use WHERE. Frequently, you'll be combining it with other keywords such as IN, LIKE, or BETWEEN.
So for your situation of using a search, you would most likely want to use the LIKE keyword, which can query your database for a field that contains parts of its data that matches the search criteria:
For example:
#Query("SELECT * FROM notes WHERE note_title LIKE :search OR note_message LIKE :search")
public List<Note> getSearchedNote(String search)
This would search your database and return a list of Notes that has either a Note Title or a Note Message that contains the search term you want.

Room DB select List of all items + total sum of these items

I have 2 queryes from ROOM DB:
#Query("SELECT * FROM basket_items")
Flowable<List<BasketItem>> getAll();
#Query("SELECT SUM(count*amount) FROM basket_items")
Flowable<Long> totalSum();
How can I merge this queryes to one query? And what type of model it will be return?
Room Queries can return POJO (not an #Entity), and therefore you can make temporary model for your DAO.
As I already asked in comments, I don't know what you're trying to achieve (as in what value you want to get from those queries).
But hopefully this example might help:
YourDao.java
#Query("SELECT name AS nameItem, (count * amount) AS countItem FROM basket_items")
Flowable<List<CountedBasketItem>> getAllCounted();
static class CountedBasketItem {
String nameItem;
Long countItem;
}
Additional Answer
What you want to return List and total sum is not possible by the query. SUM is aggregation method, you aggregate the list.
So there're 2 options that you might want to do:
Use GROUP BY in your query
Or execute those 2 Flowable and get the result.
you can create field totalSum in your pojo and use this query
#Query("SELECT *,SUM(count*amount) AS totalSum FROM basket_items")
Flowable<List<BasketItem>> getAll();
you will get all table and the field totalSum is SUM(count*amount)

Getting Error when Passing the TableName with Parameters using -Android Sqlite Room ORM

1.when trying to access the data with tablename as a parameter using method, getting below mentioned error using Room Library in android.
--> There is a problem with the query: ERROR] SQL error or missing database (no such table: table Name)
MainActivity.class
userData1= userSampleDatabase.daoAccessForUser().getItembyIdvalue("UserData","1");
DaoAccessForUser.class
#Query("select * from 'tableName' where id = :id")
List<UserData> getItembyIdvalue(String tableName,String id);
Thanks in Advance.
Room does not support dynamic replacement of the table name.
In your DAO, replace 'tableName' with the actual table name, as defined on the associated #Entity. Or, use #RawQuery instead of #Query and provide the entire SQL SELECT statement at runtime.
There is a reason why you get this error at compile time; Room check queries at compile time to ensure your application won't run into problem in runtime..
So as far as Room knows there may be no id in your table at all! To prevent your app from encountering such a problem room require you to provide table name beforehand. If this feature is essential to your project try using ORMs with Query Builder like greenDAO or dbflow
Hope you understand Room behaviour ^^
as CommonsWare suggested you can use #RawQuery
In you DaoAccessForUser.class
#RawQuery
List<UserData> getUserDataList(String query);
and you can call it like this
String tablename="UserData";
String id="1";
userData1= userSampleDatabase.daoAccessForUser().getUserDataList("select * from "+tablename+" where id = " + id);

Categories

Resources