【发布时间】:2017-07-08 12:56:19
【问题描述】:
我正在使用 Room 库将数据保存在数据库中。我想获取数据库。
使用了这个代码
private void copyFile() {
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath=getDatabasePath("photex_db.db").getAbsolutePath();
String backupDBPath = "photex_db.db";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
if (currentDB.exists()) {
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
它适用于简单的 sqlLite,但 不适用于 ROOM 库 ROOM
有什么方法可以获取数据库吗?
类在 Room 的帮助下创建数据库
@Database(entities = {ProjectDataEntity.class, SavedProjectEntity.class},
version = 2)
@TypeConverters(DateConverter.class)
public abstract class AppDatabase extends RoomDatabase {
static final String DATABASE_NAME = "photex_db";
private static AppDatabase Instance;
public abstract ProjectDataDao projectDataDao();
public abstract SavedProjectDao savedProjectDao();
public static AppDatabase getInstance(Context context) {
if (Instance == null) {
synchronized (AppDatabase.class) {
if (Instance == null) {
Instance =
Room.databaseBuilder(context.getApplicationContext(),
AppDatabase.class, DATABASE_NAME)
.build();
}
}
}
return Instance;
}
}
【问题讨论】:
-
“它在简单的 sqlLite 中工作”——不适用于许多设备或许多用户。 从不硬编码路径。 Use
getDatabasePath(), please。 “不适用于 ROOM 库”——如果您使用getDatabasePath(),它应该适用于 Room。如果您遇到问题,请提供minimal reproducible example,其中将包括您向 Room 提供有关使用什么数据库的信息的RoomDatabase。 -
@CommonsWare 我试过 getDatabasePath() 它没有帮助:(
-
然后,正如我所写,请提供minimal reproducible example,其中包括
RoomDatabase,您将在其中向 Room 提供有关使用什么数据库的信息。 -
我更新了问题,看看是不是你的意思
-
你可以查看this的答案。也许你只是错误地创建了数据库。
标签: android database android-room