无法将活动强制转换为LifecycleOwner

时间:2019-02-03 04:35:09

标签: android android-lifecycle android-livedata

我的MainActivity扩展了AppCompatActivity

public class MainActivity extends AppCompatActivity {
private WebsiteViewModel websiteViewModel;

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


      setContentView(R.layout.activity_main);

        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setHasFixedSize(true);

        final WebsiteAdapter adapter = new WebsiteAdapter();


        this.websiteViewModel = ViewModelProviders.of(this).get(WebsiteViewModel.class);

        this.websiteViewModel.getAllWebsites().observe(this, new Observer<List<Website>>() {
            @Override
            public void onChanged(@Nullable List<Website> websites) {
                adapter.setWebsites(websites);
            }
        });
        recyclerView.setAdapter(adapter);
    }
}

我面临的错误是“错误:不兼容的类型:MainActivity无法转换为LifecycleOwner。”

WebsiteViewModel

    public class WebsiteViewModel extends AndroidViewModel {
    private WebsiteRepository repository;
    private LiveData<List<Website>> allWebsites;

    public WebsiteViewModel(@NonNull Application application) {
        super(application);
        repository = new WebsiteRepository(application);
        allWebsites = repository.getAllWebsites();
    }

    public void insert(Website website) {
        repository.insert(website);
    }

    public void update(Website website) {
        repository.update(website);
    }

    public void delete(Website website) {
        repository.delete(website);
    }

    public void deleteAllWebsites() {
        repository.deleteAllWebsites();
    }

    public LiveData<List<Website>> getAllWebsites() {
        return allWebsites;
    }
}

在另一个项目中,我使用Fragment而不是Activity强制转换为生命周期所有者,并且该项目运行时没有出现此错误。但是我正在从https://codinginflow.com/tutorials/android/room-viewmodel-livedata-recyclerview-mvvm/part-6-recyclerview-adapter复制,但是我不知道为什么会有这个问题。我使用的是androidx

如果我在MainActivity中添加实现LifecycleOwner,则会收到错误“ java.lang.NoSuchMethodError:没有超级方法getLifecycle()Landroidx / lifecycle / Lifecycle;在类Landroidx / core / app / ComponentActivity中;或其父类(声明“ androidx.core.app.ComponentActivity”的内容出现在/data/app/com.example.project-2/split_lib_dependencies_apk.apk)“

3 个答案:

答案 0 :(得分:6)

尝试将您的AppCompat依赖项更新为最新的依赖项。我从更新 'androidx.appcompat:appcompat:1.0.0-alpha1'  至 'androidx.appcompat:appcompat:1.1.0-alpha03'并将其修复

答案 1 :(得分:3)

implementation 'androidx.constraintlayout:constraintlayout:2.0.0-beta2'也将问题降级为

implementation 'androidx.constraintlayout:constraintlayout:2.0.0-beta1'以避免错误

答案 2 :(得分:1)

如果您现在发现此问题,可能是因为您添加了androidx.recyclerview:recyclerview:1.1.0-*的预发布版本,该版本显然包含上游androidx core,但尚未实现Activity LifecycleOwner