有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

MainActivity cannot be converted to LifecycleOwner 我用它作为LiveCycle的所有者,但是它被拒绝了,我得到了一个错误,正如你在图片中看到的。 我处理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 "安卓.arch.lifecycle:extensions:1.0.0"
annotationProcessor "安卓.arch.lifecycle:compiler:1.0.0"

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


共 (3) 个答案

  1. # 1 楼答案

    我也犯了同样的错误。升级到androidx支持库修复了该问题。 在Android Studio内部选择:重构->;迁移到android x

  2. # 2 楼答案

    正如您所看到的hereLifecycleOwner是在支持库26.1.0中添加的。解决问题的最简单方法是升级支持库版本

  3. # 3 楼答案

    默认情况下,Support Library 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