Am building a grocery list app using Room and need to do multiple updates in a List of containing my Dao object. How can I run multiple updates in my List of objects? Should I run them in a single thread or will I have to create multiple threads for each object update? I'm currently having the issue where only the first object in the List gets updated correctly and the others are getting set to checked = false but listed = true. Once the thread is done with all transaction updates, the activity should reload. Am using AsyncTaskLoader, thanks!
Grocery DAO
package data;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Delete;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.Query;
import android.arch.persistence.room.Update;
import java.util.List;
/**
* The {@link Dao} class to run CRUD operations on the database.
*/
@Dao
public interface GroceryItemDao {
@Query("SELECT * FROM GroceryItem")
List<GroceryItem> getAllGroceries();
@Query("SELECT * FROM groceryitem WHERE is_listed = 1")
List<GroceryItem> getAllListedGroceries();
@Update
void updateGrocery(GroceryItem groceryItem);
@Insert
void insertGroceryItem(GroceryItem groceryItem);
@Delete
void delete(GroceryItem groceryItem);
}
Loader class
package loaders;
import android.content.AsyncTaskLoader;
import android.content.Context;
import android.util.Log;
import java.util.List;
import data.AppDatabase;
import data.GroceryItem;
import static utils.Constant.IS_CHECKED_FALSE;
import static utils.Constant.IS_LISTED_FALSE;
public class GroceryLoaderUpdate extends AsyncTaskLoader {
public static final String TAG = "GroceryLoaderUpdate";
private List<GroceryItem> groceryItems;
private AppDatabase db;
public GroceryLoaderUpdate(Context context, List<GroceryItem> groceryItems) {
super(context);
this.groceryItems = groceryItems;
}
@Override
protected void onStartLoading() {
forceLoad();
}
@Override
public Object loadInBackground() {
db = AppDatabase.getAppDataBase(GroceryLoaderUpdate.this.getContext());
for (GroceryItem current : groceryItems) {
if (current.isChecked()) {
current.setChecked(IS_CHECKED_FALSE);
current.setListed(IS_LISTED_FALSE);
db.groceryItemDao().updateGrocery(current);
}
}
return null;
}
}
You can update multiple objects with
@Update
public void updateGroceries(GroceryItem... groceryItem);
and then
db.groceryItemDao().updateGroceries(groceryItems.toArray(new GroceryItem[groceryItems.size()]));