Room是Google为了简化旧式的SQLite操作专门提供的
- 1、拥有SQLite的所有操作功能
- 2、使用简单(类似于Retrofit库),通过注解的方式实现相关功能。编译时自动生成实现类impl。
- 3、LiveData、LifeCycle、Paging天然融合支持。
使用Room数据库缓存网络请求数据。
新建lib_network
新建 名为 lib_network 的module
添加依赖
//网络库的封装
implementation 'com.squareup.okhttp3:okhttp:4.2.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.5.0'
//Room数据库缓存
implementation 'android.arch.persistence.room:runtime:1.1.1'
implementation "android.arch.lifecycle:extensions:1.1.1"
annotationProcessor 'android.arch.persistence.room:compiler:1.1.1'
annotationProcessor "android.arch.lifecycle:compiler:1.1.1"
指定room.schemaLocation生成的文件路径
android {
...
defaultConfig {
...
javaCompileOptions{
annotationProcessorOptions{
arguments=["room.schemaLocation":"$projectDir/schemas".toString()]
}
}
}
...
}
否则会报如下错误:
警告: Schema export directory is not provided to the annotation processor so we cannot export the schema. You can either provide
room.schemaLocation
annotation processor argument OR set exportSchema to false.
表
@Entity(tableName = "cache")
public class Cache implements Serializable {
@PrimaryKey
@NonNull
public String key;
//@ColumnInfo(name = "_data")
public byte[] data;
}
数据操作-Dao
@Dao
public interface CacheDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
long save(Cache cache);
@Query("select *from cache where `key`=:key")
Cache getCache(String key);
@Delete
int delete(Cache cache);
@Update(onConflict = OnConflictStrategy.REPLACE)
int update(Cache cache);
}
定义数据库
@Database(entities = {Cache.class}, version = 1)
public abstract class CacheDatabase extends RoomDatabase {
private static final CacheDatabase database;
static {
//创建一个内存数据库
//但是这种数据库的数据只存在于内存中,也就是进程被杀之后,数据随之丢失
//Room.inMemoryDatabaseBuilder()
database = Room.databaseBuilder(AppGlobals.getApplication(), CacheDatabase.class, "ppjoke_cache")
//是否允许在主线程进行查询
.allowMainThreadQueries()
//数据库创建和打开后的回调
//.addCallback()
//设置查询的线程池
//.setQueryExecutor()
//.openHelperFactory()
//room的日志模式
//.setJournalMode()
//数据库升级异常之后的回滚
//.fallbackToDestructiveMigration()
//数据库升级异常后根据指定版本进行回滚
//.fallbackToDestructiveMigrationFrom()
// .addMigrations(CacheDatabase.sMigration)
.build();
}
public abstract CacheDao getCache();
public static CacheDatabase get() {
return database;
}
// static Migration sMigration = new Migration(1, 3) {
// @Override
// public void migrate(@NonNull SupportSQLiteDatabase database) {
// database.execSQL("alter table teacher rename to student");
// database.execSQL("alter table teacher add column teacher_age INTEGER NOT NULL default 0");
// }
// };
}
缓存管理类CacheManager
public class CacheManager {
private static Object toObject(byte[] data) {
ByteArrayInputStream bais = null;
ObjectInputStream ois = null;
try {
bais = new ByteArrayInputStream(data);
ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bais != null) {
bais.close();
}
if (ois != null) {
ois.close();
}
} catch (Exception ignore) {
ignore.printStackTrace();
}
}
return null;
}
private static <T> byte[] toByteArray(T body) {
ByteArrayOutputStream baos = null;
ObjectOutputStream oos = null;
try {
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(body);
oos.flush();
return baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (baos != null) {
baos.close();
}
if (oos != null) {
oos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return new byte[0];
}
public static <T> void delete(String key, T body) {
Cache cache = new Cache();
cache.key = key;
cache.data = toByteArray(body);
CacheDatabase.get().getCache().delete(cache);
}
public static <T> void save(String key, T body) {
Cache cache = new Cache();
cache.key = key;
cache.data = toByteArray(body);
CacheDatabase.get().getCache().save(cache);
}
public static Object getCache(String key) {
Cache cache = CacheDatabase.get().getCache().getCache(key);
if (cache != null && cache.data != null) {
return toObject(cache.data);
}
return null;
}
}
使用
private void saveCache(T body) {
String key = TextUtils.isEmpty(cacheKey) ? generateCacheKey() : cacheKey;
CacheManager.save(key, body);
}
Object cache = CacheManager.getCache(key);