android Room基础使用

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

今天开始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();

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值