DBFlow icon indicating copy to clipboard operation
DBFlow copied to clipboard

Download remote db and use it

Open darkovski88 opened this issue 11 years ago • 2 comments

Hello, I wanted to know is it possible to use a sql file that is downloaded from the internet and saved to SD card. Does DBFlow enables such thing? Is so can someone tell me how can I do that?

darkovski88 avatar Sep 10 '15 13:09 darkovski88

Not sure about external storage, but I did it saving the database to default database directory (internal storage):

Something like that:

@Database(name = SomeDatabase.NAME, version = 1, sqlHelperClass = SqlOpenHelper.class)
public class SomeDatabase {

    private static final String DATABASE_EXTENSION = ".db";

    public static final String NAME = "somedatabase";

    public static void saveDatabase(@NonNull Context context, @NonNull byte[] database) throws IOException {

        File databaseFileDestinationFullPath = context.getDatabasePath(NAME + DATABASE_EXTENSION);

        InputStream inputStream = null;
        FileOutputStream outputStream = null;

        // try to create the directory
        File directory = databaseFileDestinationFullPath.getParentFile();

        if (!directory.mkdirs() && !directory.isDirectory()) {
            throw new IOException("Could not create the destination directory for database.");
        }

        try {
            outputStream = new FileOutputStream(databaseFileDestinationFullPath);
            inputStream = new ByteArrayInputStream(database);

            byte[] buffer = new byte[1024];

            for (int readNum; (readNum = inputStream.read(buffer)) != -1; ) {
                outputStream.write(buffer, 0, readNum);
            }

            // opens the database
            FlowManager.init(context);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }

                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                // nothing to do
            }
        }
    }
}

On my SplashScreenActivity, I check if the database file exists.

* If it exists just call FlowManager.init
* If not, download the database and save it using the static method. 

andrecrispim avatar Sep 10 '15 20:09 andrecrispim

related to #415

darkovski88 avatar Oct 05 '15 09:10 darkovski88