Saving a SQLite database in Android tablet internal memory (API 23)

霸气de小男生 提交于 2019-12-13 17:17:53

问题


I am an abject novice in Android app development. However, my current project requires me to make an app that records field observations (am a research scientist), save them to a SQLite database - these will be sent to a central location for processing. The app will be used on tablets.

Currently, I am using Android Studio, and when I emulate the app functions, everything works as planned and using DB Browser for SQLite, I can see that the values are being recorded correctly in the database.

Doing research (an example is the answer here), I am aware that the the database (.db) file is saved in the directory path:

/data/data/<your.app.package>/databases/foo.db

Of course, this is accessible in Android Studio, but my understanding is that unless the device is rooted, these files are inaccessible in an actual device. For various reasons, this is not an option for the work that I am involved with.

In researching, I came across a method to back up the database, and save the back up database to an SD card, as in the answer to the question Backup/restore sqlite db in android [duplicate] and the duplicate target Android backup/restore: how to backup an internal database?.

Saving to external storage devices such as SD cards in APIs of 23 and above now require considerable more permissions to write to external sources (above and beyond what has always been required in the Manifest). For many reasons, this option is not optimal.

In this answer, the backup is saved on the SD card:

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();

But, my question (possibly a brain-fart type) is - is it possible to have the backup saved to an internal file of the device (e.g. Documents folder), and would the permissions still be required?


回答1:


It's not complicated to achieve the pemission's flow. Here is a class that I created for help. You have to extend your MainActivity from this, and then you can call:

verifyStoragePermissions(new Runnable() {
    @Override
    public void run() {
        //backup your db here...
    }
});

It works for all Android versions using android support library.



来源:https://stackoverflow.com/questions/40104793/saving-a-sqlite-database-in-android-tablet-internal-memory-api-23

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!