Search code examples
androidandroid-sqlite

Get app sqlite database programmatically in file


I want to upload my sqlite DB file to DropBox. But before that I need to get the sqlite Db file in code. How can I do this on any device? I checked on this link, and it says that the user needs root permissions to access the database.

So in short:

How can I access my sqlite database with non rooted devices? eg File f = new File("path_to_db_file");

If that approach is impossible, how can I save my app database in a place that I will be able to gain access to it?

Please let me know if I can explain anything. Thank you in advance


Solution

  • Yes you can, something like this worked for me without root permission:

    File Db = new File("/data/data/your.package/databases/yourdatabasename");        
    Date d = new Date();         
    
    File file = new File("your_destination.db");
    file.setWritable(true);
    
    copyFile(new FileInputStream(Db), new FileOutputStream(file));
    

    Copy file is a function like this, and works in both directions DB->File and File->DB:

    public static void copyFile(FileInputStream fromFile, FileOutputStream toFile) throws IOException {
        FileChannel fromChannel = null;
        FileChannel toChannel = null;
        try {
            fromChannel = fromFile.getChannel();
            toChannel = toFile.getChannel();
            fromChannel.transferTo(0, fromChannel.size(), toChannel);
        } finally {
            try {
                if (fromChannel != null) {
                    fromChannel.close();
                }
            } finally {
                if (toChannel != null) {
                    toChannel.close();
                }
            }
        }
    }