Уроки программирования для Android

Android Class - просто и понятно о программировании для Android на языке Java

How to copy database from assets folder with Room Persistence Library for Android

Комментарии: 0
During migration from pardom's ActiveAndroid ORM to Room for Android from Google I came across the following problem. If I have prepopulated database, how can I initialize it from db file located inside assets folder in my project. Fortunately there is a simple solution (some code was copied from ActiveAndroid sources).
package com.app.names.db;

import android.arch.persistence.room.Room;
import android.content.Context;
import android.util.Log;

import com.app.names.App;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import static com.app.names.db.AppDatabase.DATABASE_NAME;

public class DB {
    private static final String TAG = DB.class.getSimpleName();

    private AppDatabase mAppDataBase;

    private static class Holder {
        private static final DB INSTANCE = new DB();
    }

    public static DB getInstance() {
        return Holder.INSTANCE;
    }

    private DB() {
        //call method that check if database not exists and copy prepopulated file from assets
        copyAttachedDatabase(App.getAppContext(), DATABASE_NAME);
        mAppDataBase = Room.databaseBuilder(App.getAppContext(),
                AppDatabase.class, DATABASE_NAME).build();
    }

    public AppDatabase getDB() {
        return mAppDataBase;
    }


    private void copyAttachedDatabase(Context context, String databaseName) {
        final File dbPath = context.getDatabasePath(databaseName);

        // If the database already exists, return
        if (dbPath.exists()) {
            return;
        }

        // Make sure we have a path to the file
        dbPath.getParentFile().mkdirs();

        // Try to copy database file
        try {
            final InputStream inputStream = context.getAssets().open(databaseName);
            final OutputStream output = new FileOutputStream(dbPath);

            byte[] buffer = new byte[8192];
            int length;

            while ((length = inputStream.read(buffer, 0, 8192)) > 0) {
                output.write(buffer, 0, length);
            }

            output.flush();
            output.close();
            inputStream.close();
        }
        catch (IOException e) {
            Log.d(TAG, "Failed to open file", e);
            e.printStackTrace();
        }
    }

}