1.表格
实现方式 | BasicSample | BasicSample | PersistenceContentProviderSample | ||
---|---|---|---|---|---|
对应某个表的增删改查 | Dao | @Dao 使用注解的方式实现 CRUD(接口类似 retrofit) | ProductDao | UserDao | CheeseDao |
对应某个表的字段实体 | Entity | @Entity(tableName = "${tbName}") | ProductEntity | UserEntity | CheeseEntity |
绑定数据库和表 | Database | @Database(entities = {${*Entity.class}}, version = 1) ~ extends RoomDatabase | AppDatabase | UsersDatabase | SampleDatabase |
对数据库初始化,绑定关系 | ViewModel | extends ViewModel(AndroidViewModel) | ProductListViewModel | UserViewModel | |
得到 ViewModel 的实例 | Provider.Factory~extends ViewModelProvider.NewInstanceFactory | implements ViewModelProvider.Factory | ProductViewModel.Factory | ViewModelFactory | |
ContentProvider | extends ContentProvider | 无 | 无 | SampleContentProvider | |
主 View | Activity | extends LifecycleActivity | MainActivity | UserActivity | |
Injection | provideViewModelFactory | 无 | Injection | ||
RxJava | 使用mDisposable对数据库进行操作 | 无 | UserActivity | ||
绑定数据 | DataBinding | 在 xml 使用<data>标签绑定 model | comment_item.xml | 无 |
view 中获取数据
final ProductListViewModel viewModel =
ViewModelProviders.of(this).get(ProductListViewModel.class);
viewModel.getProducts().observe(this, new Observer<List<ProductEntity>>() {
@Override
public void onChanged(@Nullable List<ProductEntity> myProducts) {
if (myProducts != null) {
mBinding.setIsLoading(false);
mProductAdapter.setProductList(myProducts);
} else {
mBinding.setIsLoading(true);
}
}
});
//BasicRxJavaSample:
//得到 ViewModelFactory
public static ViewModelFactory provideViewModelFactory(Context context) {
UserDataSource dataSource = provideUserDataSource(context);
return new ViewModelFactory(dataSource);
}
//得到 factory 实例
mViewModelFactory = Injection.provideViewModelFactory(this);
//使用ViewModelProviders获取 viewModel 实例
mViewModel = ViewModelProviders.of(this, mViewModelFactory).get(UserViewModel.class);
//使用 RxJava 读取数据库
mDisposable.add(mViewModel.getUserName()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<String>() {
@Override
public void accept(String userName) throws Exception {
mUserName.setText(userName);
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
Log.e(TAG, "Unable to update username", throwable);
}
}));