Search code examples
androidandroid-architecture-components

invalid parameter type. Must be one and instanceof LifecycleOwner


I am trying to use the lifeCycleOwner and lifecycleObserve . I am getting the following exception when i call lifecycleOwner.getLifecycle().addObserver(this);

invalid parameter type. Must be one and instanceof LifecycleOwner

the code as shown below

public class TestActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_activity);

        new  TestObserver(this,this);
    }   
    }

public class TestObserver implements LifecycleObserver{

  public TestObserver(LifecycleOwner lifecycleOwner, Context context){
        lifecycleOwner.getLifecycle().addObserver(this);
    }
}

Edited: as requested the Build.gradle file

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.example.test"
        minSdkVersion 14
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }


    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:design:27.1.1'
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support:cardview-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'

    // ViewModel and LiveData ,lifecycleObserver
    implementation 'android.arch.lifecycle:extensions:1.1.1'
    implementation "android.arch.lifecycle:runtime:1.1.1"

}

apply plugin: 'com.google.gms.google-services'
apply plugin: 'io.fabric'

Solution

  • When you override onCreate or other events in the LifecycleObserver, don't pass any argument to the method.

    This cause your error :

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    protected void onCreate(Bundle savedInstanceState)
    

    This is the right declaration :

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    protected void onCreate()