Incompatible type: MainActivity cannot be converted to LifecycleOwner… here is a solution to the problem.
Incompatible type: MainActivity cannot be converted to LifecycleOwner
MainActivity cannot be converted to LifecycleOwner
I used it as a LiveCycle owner, but it was rejected and I got an error as shown in the image.
I’m working on API 25
and I think this issue might be related to this version
This is information about my SDK
compileSdkVersion 25
buildToolsVersion '25.0.2'
Here is my code :
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);
}
});
}
I put the LiveData dependencies into my Gradle
compile "android.arch.lifecycle:extensions:1.0.0"
annotationProcessor "android.arch.lifecycle:compiler:1.0.0"
If anyone knows the cause of the problem, please let me know
Solution
Support Library 26.1.0 and later Fragments and Activities already implement the LifecycleOwner interface by default
But in version 25 you need to implement the LifecycleOwner interface
For example
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;
}
}