github地址:https://github.com/cwwei2005/MVVMForJava
数据来源:豆瓣api。
1、room
1.1、创建一个类继承roomdatabase,一般使用单例模式:
@Database(entities = {Theater.class}, version = 1, exportSchema = false)
public abstract class MyDatabase extends RoomDatabase {
private static MyDatabase instance;
public static MyDatabase getInstance(){
if (instance == null){
synchronized (MyDatabase.class){
if (instance == null) instance = buildDatabase();
}
}
return instance;
}
private static MyDatabase buildDatabase() {
return Room.databaseBuilder(App.instance, MyDatabase.class, "test.db").build();
}
//
public abstract TheaterDao theaterDao();
}
注意的是,java里需要定义:exportSchema = false,kotlin试过不需要。
1.2、创建一个DAO
@Dao
public interface TheaterDao {
@Insert
void insert(Theater theater);
@Insert(onConflict = OnConflictStrategy.REPLACE)
void replaceInsert(Theater theater);
@Insert
void insertAll(List<Theater> theaters);
@Update
void update(Theater theater);
@Update
void updateAll(List<Theater> theaters);
@Delete
void delete(Theater theater);
@Delete
void deleteAll(List<Theater> theaters);
@Query("select * from theater") //查询所有
Theater getSingle();
@Query("select * from theater") //查询所有
LiveData<Theater> getSingle2();
}
有没有人告诉我,为什么DAO不需要表名?
1.3、bean类
@Entity(tableName = "theater"/*, indices = {@Index(value = {"title"}, unique = true)}*/)
@TypeConverters(Theater.SubjectsBeanConverters.class)
public class Theater extends BaseObservable {
@PrimaryKey(autoGenerate = true)
public int id;
private int count;
private int start;
private int total;
private String title;
private List<SubjectsBean> subjects;
......
}
要注意的是,如果要在布局引用相关属性,需要添加set和get方法。kotlin不需要使用data class即可。
2、Repository
实现了几个方法:获取网络对象,对象持久化,网络状态返回。
3、activity
3.1、binding的初始化:
vm = ViewModelProviders.of(this).get(ViewModelImpl.class); binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
3.2、初始化RecyclerView
这里使用一个开源框架XRecyclerView,可以实现上拉加载下拉刷新功能。
3.3、数据初始化
获取可观察的数据和网络状态,更新RecyclerView。
recyclerview也利用了databinding的@BindingAdapter注解结合glide显示图片。
@BindingAdapter({"app:imageUrl", "app:placeHolder", "app:error"})
public static void setImage(ImageView imageView, String url, Drawable holderDrawable, Drawable errorDrawable) {
Glide.with(imageView.getContext())
.load(url)
.placeholder(holderDrawable)
.error(errorDrawable)
.into(imageView);
}