Marwa Eltayeb
Marwa Eltayeb

Reputation: 2131

incompatible types: MainActivity cannot be converted to LifecycleOwner

MainActivity cannot be converted to LifecycleOwner I used this as LiveCycle Owner, but it is rejected and I got an error as you see in the picture. I work on Api 25 and I this the problem may be related to this version This is info about my sdk

compileSdkVersion 25
buildToolsVersion '25.0.2'

This 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 LiveData dependencies in my Gradle

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

If anyone knows the reason for the problem, let me know please

Upvotes: 2

Views: 4440

Answers (3)

AmrDeveloper
AmrDeveloper

Reputation: 4712

Fragments and Activities in Support Library 26.1.0 and later already implement the LifecycleOwner interface by default

but in version 25 you need to implement 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;
    }
}

Source : Handling lifecycles with lifecycle-aware components

Upvotes: 2

Oleg Barchuk
Oleg Barchuk

Reputation: 31

Had the same error. Upgrading to androidx support libraries fixed the issue. Choose inside Android Studio: Refactor -> Migrate to android x

Upvotes: 0

Rene Ferrari
Rene Ferrari

Reputation: 4206

As you can read here the LifecycleOwner was added in support library 26.1.0. Easiest way to fix your issue would be upgrading your support library version.

Upvotes: 2

Related Questions