不兼容的类型:MainActivity无法转换为LifecycleOwner

时间:2018-07-04 21:25:28

标签: java android android-gradle android-room android-livedata

MainActivity cannot be converted to LifecycleOwner 我以LiveCycle Owner的身份使用它,但是它被拒绝了,您在图片中看到了一个错误。 我在Api 25上工作,这可能与该版本有关 这是关于我的SDK的信息

compileSdkVersion 25
buildToolsVersion '25.0.2'

这是我的代码:

private void retrieveTasks() {
    Log.d(TAG, "Actively retrieving the tasks from the DataBase");
    // Extract all this logic outside the Executor and remove the Executor
    // Fix compile issue by wrapping the return type with LiveData
    LiveData<List<TaskEntry>> tasks = mDb.taskDao().loadAllTasks();
    // Observe tasks and move the logic from runOnUiThread to onChanged
    tasks.observe(this, new Observer<List<TaskEntry>>() {
        @Override
        public void onChanged(@Nullable List<TaskEntry> taskEntries) {
            Log.d(TAG, "Receiving database update from LiveData");
            mAdapter.setTasks(taskEntries);
        }
    });
}

我将LiveData依赖项放入了Gradle

compile "android.arch.lifecycle:extensions:1.0.0"
annotationProcessor "android.arch.lifecycle:compiler:1.0.0"

如果有人知道问题的原因,请告诉我

3 个答案:

答案 0 :(得分:2)

您可以读到hereLifecycleOwner已添加到支持库26.1.0中。解决问题的最简单方法是升级支持库版本。

答案 1 :(得分:1)

好问题

默认情况下,支持库26.1.0和更高版本中的片段和活动已经实现了LifecycleOwner接口

但是在版本25中,您需要实现LifecycleOwner接口     例如

public class MyActivity extends Activity implements LifecycleOwner {
    private LifecycleRegistry mLifecycleRegistry;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mLifecycleRegistry = new LifecycleRegistry(this);
        mLifecycleRegistry.markState(Lifecycle.State.CREATED);
    }

    @Override
    public void onStart() {
        super.onStart();
        mLifecycleRegistry.markState(Lifecycle.State.STARTED);
    }

    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }
}

来源:Handling lifecycles with lifecycle-aware components

答案 2 :(得分:0)

有相同的错误。升级到androidx支持库可解决此问题。 在Android Studio中选择:重构->迁移到android x