我的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)“
尝试将AppCompat
依赖项更新为最新版本。我从'androidx.appcompat:appcompat:1.0.0-alpha1'
更新到'androidx.appcompat:appcompat:1.1.0-alpha03'
并修复了它
如果你现在发现这个,可能是因为你添加了一个预发布版本的androidx.recyclerview:recyclerview:1.1.0-*
,它显然包含没有core
实现Activity
的上游androidx LifecycleOwner
。