Android Room insertAll issues

37.3k views Asked by At

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

2

There are 2 answers

5
joao86 On BEST ANSWER

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()); 
        }
});
0
Dipendra Sharma On

OnConflict Property must be added.

@Insert(onConflict = OnConflictStrategy.REPLACE)