Skip to content Skip to sidebar Skip to footer

Room Not Returning Duplicates

So I have a room database all set up, everything is fine, so I can make queries and inserts, delete etc no problems, however i've just run into a situation where id like to return

Solution 1:

Edit:

The SQLiteDatabase always presents the results as a Cursor in a table format that resembles that of a SQL database.

Source : Google Developer Training

Before the results are returned by the query, the results are stored in a table, and if there are rows with duplicate primary keys, they would be omitted by default.

To achieve what you intend, you can execute a query to find single element by id in loop and append the result to a list.

Updated DAO method:

@Query("SELECT * FROM card WHERE cardId=:cardId")
LiveData<Card> getCardById(Integer cardId);

Update Repository method:

public LiveData<List<Card>> getCardsByIds(List<Integer> cardIds){
    Listlist=newArrayList();
    for(Integer cardId: cardIds){
      list.append(cardDao.getCardById(cardId));
    }
    return list;
}

Hope this helps.

Original Answer:

If id is the primary key of your model, It doesn't allow duplicate data to be entered. Hence while retrieving you might find duplicates missing.

If you have id with duplicate, create another attribute for primary key. (use autogenerate if you don't have any primary key attribute)

A primary key is by default UNIQUE and NOT NULL.

Post a Comment for "Room Not Returning Duplicates"