活动无法转换为LifecycleOwner [英] Activity cannot be converted to LifecycleOwner
问题描述
我想将Room与LiveData一起使用,在其他项目中我已经使用过它,但是在这一项目中,我无法使其正常工作.当我尝试观察实时数据时,它无法将我的活动转换为生命周期活动,但是,我正在使用AppCompatActivity,甚至尝试覆盖getLifecycle方法(在以前的项目中对我有用).我什至尝试使用AndroidX,但仍然存在相同的问题:(
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;
}
这是我的gradle文件:
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'
这是我的道:
@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.
添加代码
推荐答案
您不需要使用
mLifecycleRegistry = new LifecycleRegistry(this);
mLifecycleRegistry.markState(Lifecycle.State.CREATED);
自此,新的AppcompatActivity
已经是lifecyclerOwner
.
您还观察到类对象,这是不正确的. actMain.class
是一个类对象.
您应该具有:
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) {}
});
这篇关于活动无法转换为LifecycleOwner的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!