I have a LiveData<List<Storage>> in my StorageViewModel, I want to get this list in an activity in order to perform a get(id) on it.
Though so far I can only achieve one way to get the this List<Storage> without it being null, except that way does not feel efficient to me.
Why does my second method not work? Am I forgetting declaring something final?
EDIT: my second method retrieves an object coming from an async call on a ROOM repository, I require some sort of callback to get the right instance as it seems. Then again, perhaps the way could be more efficient.
ViewModel Class
public class StorageViewModel extends AndroidViewModel
{
StorageRepository _repository;
LiveData<List<Storage>> _storages;
public ObservableField<String> storageName = new ObservableField<>("");
public ObservableField<String> storageLoc = new ObservableField<>("");
public StorageViewModel(Application application)
{
super(application);
_repository = new StorageRepository(application);
_storages = _repository.getAllStorages();
}
public LiveData<List<Storage>> getStorages()
{
return _storages;
}
public void addStorage(String storageName, String storageLocation)
{
_repository.insert(new Storage(storageName, storageLocation));
}
}
Working method in StorageActivity Class (storages != null)
void setActivityElements()
{
int id = (int) getIntent().getExtras().get("storageID");
storageVM.getStorages().observe(this, new Observer<List<Storage>>()
{
@Override
public void onChanged(@Nullable final List<Storage> storages)
{
Storage storage = storages.get(id); // storages != null
}
});
}
Not working method in StorageActivity Class (storages == null)
void setActivityElements()
{
int id = (int) getIntent().getExtras().get("storageID");
List<Storage> storages = storageVM.getStorages().getValue(); // storages == null
Storage storage = storages.get(id);
}