我是 Android 应用程序开发的新手。然而,我目前的项目要求我制作一个应用程序来记录实地观察(我是一名研究科学家),将它们保存到 SQLite 数据库中——这些将被发送到一个中央位置进行处理。该应用将在平板电脑上使用。
目前,我正在使用 Android Studio,当我模拟应用程序功能时,一切都按计划进行并使用 DB Browser for SQLite ,我可以看到这些值被正确地记录在数据库中。
做研究(一个例子是答案 here ),我知道数据库( .db
)文件保存在目录路径中:
/data/data/<your.app.package>/databases/foo.db
当然,这在 Android Studio 中是可以访问的,但我的理解是,除非设备已 root,否则这些文件在实际设备中是无法访问的。由于各种原因,这不是我参与的工作的选择。
在研究中,我遇到了一种备份数据库的方法,并将备份的数据库保存到SD卡中,如Backup/restore sqlite db in android [duplicate]问题的答案。和重复目标 Android backup/restore: how to backup an internal database? .
在 23 及更高版本的 API 中保存到 SD 卡等外部存储设备现在需要相当多的权限才能写入外部源(超出 list 中一直要求的权限)。由于多种原因,此选项不是最佳选择。
在this answer ,备份保存在SD卡上:
final String inFileName = "/data/data/<your.app.package>/databases/foo.db";
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);
String outFileName = Environment.getExternalStorageDirectory()+"/database_copy.db";
// Open the empty db as the output stream
OutputStream output = new FileOutputStream(outFileName);
// Transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer))>0){
output.write(buffer, 0, length);
}
// Close the streams
output.flush();
output.close();
fis.close();
但是,我的问题(可能是脑放问题)是 - 是否可以将备份保存到设备的内部文件(例如 Documents 文件夹),是否仍然需要权限?强>
最佳答案
实现权限的流程并不复杂。 Here is a class我创建的帮助。您必须从此扩展您的 MainActivity,然后您可以调用:
verifyStoragePermissions(new Runnable() {
@Override
public void run() {
//backup your db here...
}
});
它适用于所有使用 android 支持库的 Android 版本。
关于android - 在 Android 平板电脑内存中保存 SQLite 数据库(API 23),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40104793/