I would like to use Room with LiveData, and in other projects I already used it, but in this one, I can not get it to work. It can't convert my activity into Lifecycle activity when I try to observe the livedata, however, I'm using the AppCompatActivity, and I even tried to Override the getLifecycle method (which worked for me in previous projects). I even tried with AndroidX but still the same issue :(
Here my activity (Part of it):
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleRegistry;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
private LifecycleRegistry mLifecycleRegistry;
public class actMain extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLifecycleRegistry = new LifecycleRegistry(this);
mLifecycleRegistry.markState(Lifecycle.State.CREATED);
}
@Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
//Firebase
db = FirebaseFirestore.getInstance();
mLifecycleRegistry.markState(Lifecycle.State.STARTED);
alarmViewModel = ViewModelProviders.of(this).get(AlarmViewModel.class);
alarmViewModel.getAlarmList().observe(actMain.class, new
Observer<List<Alarm>>() {
@Override
public void onChanged(@Nullable List<Alarm> alarms) {
}
});
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
Here is my gradle file:
implementation 'androidx.room:room-runtime:2.0.0-alpha1'
annotationProcessor 'androidx.room:room-compiler:2.0.0-alpha1'
implementation 'com.google.android.material:material:1.0.0-alpha3'
implementation 'androidx.lifecycle:lifecycle-viewmodel:2.0.0-alpha1'
implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0-alpha1'
And here is my Dao:
@Dao
public interface AlarmDao {
@Query("SELECT * FROM alarm")
LiveData<List<Alarm>> getAllAlarm();
@Insert
void insert(Alarm... alarms);
@Update
void update(Alarm... alarms);
@Delete
void delete(Alarm... alarms);
}
I tried every suggestion here including mine, but I can not figure out what is the issue in this case.
Edit: Code added
You don't need to use
mLifecycleRegistry = new LifecycleRegistry(this);
mLifecycleRegistry.markState(Lifecycle.State.CREATED);
Since, new AppcompatActivity
is already lifecyclerOwner
.
You also observe class object, which is incorrect. actMain.class
is a class object.
You should have:
alarmViewModel.getAlarmList().observe(this, new Observer<List<Alarm>>() {
@Override
public void onChanged(@Nullable List<Alarm> alarms) {}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With