今天开始Jetpack第一篇!
因为正好要先用数据库,所以先看ROOM!
这篇只是能跑起来的,基础中的基础,细节以后写!
上!
一、大概先了解
ROOM主要对象为3类:
用注解表示分别是:@Database、@Dao、@Entity
各自代表,数据库、Dao对象,和实体对象(表);
二、建个对象
@Entity
public class NotificationEntity {
@PrimaryKey(autoGenerate = true)
Long id;
@ColumnInfo
String type;
@ColumnInfo
String beanId;
@ColumnInfo
String title;
@ColumnInfo
String summary;
@ColumnInfo
Date date;
public NotificationEntity(String type, String beanId, String title, String summary, Date date) {
this.type = type;
this.beanId = beanId;
this.title = title;
this.summary = summary;
this.date = date;
}
@Override
public String toString() {
return "NotificationEntity{" +
"id=" + id +
", type='" + type + '\'' +
", beanId='" + beanId + '\'' +
", title='" + title + '\'' +
", summary='" + summary + '\'' +
", date=" + date +
'}';
}
}
三、建个Dao
@Dao
public interface NotificationDao {
@Insert
void insert(NotificationEntity entity);
@Delete
void delete(NotificationEntity entity);
@Query("SELECT * from NotificationEntity ORDER BY date DESC")
List<NotificationEntity> loadAll();
@Update
void update(NotificationEntity entity);
}
四、建个数据库
@Database(entities = {NotificationEntity.class}, version = 1, exportSchema = false)
@TypeConverters(DateConverter.class)
public abstract class AppDataBase extends RoomDatabase {
public abstract NotificationDao notificationDao();
private static AppDataBase I;
public static AppDataBase getI(Context context) {
if (I == null) {
synchronized (AppDataBase.class) {
if (I == null) {
I = Room.databaseBuilder(context.getApplicationContext(),
AppDataBase.class,
"app_db").allowMainThreadQueries().build();
}
}
}
return I;
}
}
五、建个TypeConverter,转换日期
public class DateConverter {
@TypeConverter
public static Date revertDate(long value) {
return new Date(value);
}
@TypeConverter
public static long converterDate(Date value) {
return value.getTime();
}
}
六、调用
List<NotificationEntity> list = AppDataBase.getI(TestNotificationActivity.this)
.notificationDao()
.loadAll();

本文是关于Android Jetpack组件Room的初步介绍,涵盖了数据库、Dao对象和实体对象的基础创建,包括@Database、@Dao、@Entity注解的使用,以及TypeConverter用于日期转换的方法,适合初学者快速上手。
563

被折叠的 条评论
为什么被折叠?



