Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Room insertAll issues

I'm starting using Android Room and I'm having some troubles.

I have an ArrayList of 7 Orders and when I call insertAll(List orders) only 4 orders are inserted into the database.

How can I debug the insert query in order to find what is blocking ?

Thanks

like image 582
Jérôme Avatar asked Aug 28 '17 16:08

Jérôme


People also ask

Is Android room an ORM?

Room is an ORM, Object Relational Mapping library. In other words, Room will map our database objects to Java objects. Room provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite. In case of SQLite, There is no compile time verification of raw SQLite queries.

What is Dao in room?

When you use the Room persistence library to store your app's data, you interact with the stored data by defining data access objects, or DAOs. Each DAO includes methods that offer abstract access to your app's database. At compile time, Room automatically generates implementations of the DAOs that you define.

What is room DB Android?

Room is a persistence library that provides an abstraction layer over the SQLite database to allow a more robust database. With the help of room, we can easily create the database and perform CRUD operations very easily.


2 Answers

The calls done by Room are not synchronous so probably when you perform

List<Order> myOrders = mDb.getOrderDao().getAll()

it is still inserting the orders.

Try this

@Dao 
public interface OrderDao { 
    @Insert(onConflict = OnConflictStrategy.REPLACE) 
    public long insertOrder(Order order); 

    @Insert(onConflict = OnConflictStrategy.REPLACE) 
    void insertAllOrders(List<Order> order); 

    @Query("SELECT * FROM orders") 
    List<Order> getAll(); 
 }

@Entity(tableName = TABLE_NAME) 
public class Order { 
   public static final String TABLE_NAME = "orders"; 
   @PrimaryKey (autoGenerate = true)
   private int id; 
   @SerializedName("order_number") 
   @ColumnInfo(name = "order_number") 
   private String orderNumber; 
} 

// Call 
mDb.getOrderDao().insertAllOrders(orders);
Log.d(TAG, "inserted all");

Executor executor = Executors.newSingleThreadExecutor();

executor.execute(new Runnable() {
        @Override
        public void run() {

             List<Order> myOrders = mDb.getOrderDao().getAll();
             Log.d(TAG, "Orders nr = " + myOrders.size()); 
        }
});
like image 94
joao86 Avatar answered Oct 18 '22 07:10

joao86


OnConflict Property must be added.

@Insert(onConflict = OnConflictStrategy.REPLACE) 
like image 8
Dipendra Sharma Avatar answered Oct 18 '22 07:10

Dipendra Sharma