My usage currently is to store 5 specific button's info into a database (room) to persist it across reboots. My current usage doesn't rely on changes of the data because the only one changing the data is the user upon long press of the button (then i update the database). Hence I do not need a LiveData variable, and this is making it difficult for me to initialize my ViewModel.
Essentially, since the LiveData objects only update on change, my data never gets initialized. Thus the app always will cause a null-pointer on startup.
I'll share a gist of my setup so far bellow. I'm hoping there is some way to make this work where I don't have to observe any LiveData object, and I can just grab data when I instantiate the Model.
Entity:
@Entity(tableName = "myEntity")
public class MyEntity {
@PrimaryKey
public int buttonID;
// other fields...
}
DAO:
@Dao
interface MyDAO {
@Query("Select * from myDB")
LiveData<List<MyEntity>> getEntityList();
// I think this needs to change to just List<MyEntity>?
// also insert and update here...
}
Repository:
class MyRepository {
private MyDAO myDAO;
private LiveData<List<MyEntity>> allEntities;
MyRepository(Application application) {
MyDatabase db = MyDatabase.getInstance(application);
myDAO = db.myDAO();
allEntities = myDAO.getAllEntities();
}
LiveData<List<MyEntity>> getAllEntities() { return allEntities; }
// Update entity...
}
ViewModel:
public class ViewModel extends AndroidViewModel {
private MyRepository repository;
private List<MyEntity> tempList;
private HashMap<MyEntity> allEntities;
public ViewModel (Application application) {
super(application);
repository = new MyRepository(application);
Observer<List<MyEntity>> observer = data -> tempList = data;
ObserveOnce(repository.getAllEntities(), observer); // ObserveOnce implementation found in this answer: https://stackoverflow.com/a/59845763/10013384
allEntities = new HashMap<>();
for (int i = 0; i < tempList.size(); i++) { // Nullpointer here, as tempList doesn't have any items yet.
allEntities.put(tempList.get(i).buttonID, templist.get(i));
}
}
// getter and update methods...
}
Activity:
// ...
protected void onCreate(Bundle savedInstanceState) {
// ...
viewModel = new ViewModelProvider(this).get(ViewModel.class);
// Initialize UI views with data from ViewModel
}
Then in the respective listeners:
@Override
public boolean onLongClick(View v) {
int index = (Integer) v.getTag();
data.get(index).foo = fooNewUIData;
ButtonArray[index].setText(fooNewUIData);
ViewModel.update(data.get(index)); // if updated, update the ViewModel and the database
}