0

I have a static sqlite db. How could I include it into the app? Where should i put it in my project folder? How should I access it from DatabaseHandler?

Everything I found on the web was using sqlite only for creating a new db and storing user or temp data in it, but not using existing db with predefined data.

Official Google docs does not tell how to do that.

adsfasdf
  • 9
  • 1
  • 1
    Simply put it in your `assets` folder. Then copy it to your app database path, if not existing. Use it. Be happy. – Phantômaxx Jun 27 '15 at 22:42

1 Answers1

0

Handling this case is basically just doing a file copy.

The tricky part is

  • To create the database when needed only (otherwise just open it)
  • To implement the upgrade logic

I wrote a sample Helper class that demonstrate how to load a database from your assets.

public abstract class SQLiteAssetHelper extends SQLiteOpenHelper {

    // ----------------------------------
    // CONSTANTS
    // ----------------------------------

    private static final String DATABASE_DIR_NAME = "databases";

    // ----------------------------------
    // ATTRIBUTES
    // ----------------------------------

    private final Context mContext;
    private final CursorFactory mFactory;

    private SQLiteDatabase mDatabase;

    private String mDatabaseName;
    private String mDatabaseAssetPath;
    private String mDatabaseDiskPath;

    private boolean mIsProcessingDatabaseCreation; // Database creation may take some time

    // ----------------------------------
    // CONSTRUCTORS
    // ----------------------------------

    public SQLiteAssetHelper(Context context, String name, CursorFactory factory, String destinationPath, int version) {
        super(context, name, factory, version);

        mContext = context;
        mFactory = factory;

        mDatabaseName = name;

        mDatabaseAssetPath = DATABASE_DIR_NAME + "/" + name;
        if (destinationPath == null) {
            mDatabaseDiskPath = context.getApplicationInfo().dataDir + "/" + DATABASE_DIR_NAME;
        } else {
            mDatabaseDiskPath = destinationPath;
        }
    }

    // ----------------------------------
    // OVERRIDEN METHODS
    // ----------------------------------

    @Override
    public synchronized SQLiteDatabase getWritableDatabase() {
        if (mDatabase != null && mDatabase.isOpen() && !mDatabase.isReadOnly()) {
            // the database is already open and writable
            return mDatabase;
        }

        if (mIsProcessingDatabaseCreation) {
            throw new IllegalStateException("getWritableDatabase is still processing");
        }

        SQLiteDatabase db = null;
        boolean isDatabaseLoaded = false;

        try {
            mIsProcessingDatabaseCreation = true;
            db = createOrOpenDatabase();
            // you should probably check for database new version and process upgrade if necessary
            onOpen(db);
            isDatabaseLoaded = true;
            return db;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            mIsProcessingDatabaseCreation = false;
            if (isDatabaseLoaded) {
                if (mDatabase != null) {
                    try {
                        mDatabase.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                mDatabase = db;
            } else {
                if (db != null) db.close();
            }
        }
    }

    @Override
    public final void onCreate(SQLiteDatabase db) {
        // getWritableDatabase() actually handles database creation so nothing to code here
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO implement your upgrade logic here
    }

    // ----------------------------------
    // PRIVATE METHODS
    // ----------------------------------

    private void copyDatabaseFromAssets() throws IOException {

        String dest = mDatabaseDiskPath + "/" + mDatabaseName;
        String path = mDatabaseAssetPath;

        InputStream is = mContext.getAssets().open(path);

        File databaseDestinationDir = new File(mDatabaseDiskPath + "/");
        if (!databaseDestinationDir.exists()) {
            databaseDestinationDir.mkdir();
        }
        IOUtils.copy(is, new FileOutputStream(dest));
    }

    private SQLiteDatabase createOrOpenDatabase() throws IOException {

        SQLiteDatabase db = null;
        File file = new File (mDatabaseDiskPath + "/" + mDatabaseName);
        if (file.exists()) {
            db = openDatabase();
        }

        if (db != null) {
            return db;
        } else {
            copyDatabaseFromAssets();
            db = openDatabase();
            return db;
        }
    }

    private SQLiteDatabase openDatabase() {
        try {
            SQLiteDatabase db = SQLiteDatabase.openDatabase(
                    mDatabaseDiskPath + "/" + mDatabaseName, mFactory, SQLiteDatabase.OPEN_READWRITE);
            return db;
        } catch (SQLiteException e) {
            e.printStackTrace();
            return null;
        }
    }

    // ----------------------------------
    // NESTED CLASSES
    // ----------------------------------

    private static class IOUtils {

        private static final int BUFFER_SIZE = 1024;

        public static void copy(InputStream in, OutputStream outs) throws IOException {
            int length;
            byte[] buffer = new byte[BUFFER_SIZE];

            while ((length = in.read(buffer)) > 0) {
                outs.write(buffer, 0, length);
            }

            outs.flush();
            outs.close();
            in.close();
        }

    }; // IOUtils

}

Then you only have to create a class that extends from the one above like this :

public class MyDbHelper extends SQLiteAssetHelper {

    // ----------------------------------
    // CONSTANTS
    // ----------------------------------

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_FILE_NAME = "test.db";

    // ----------------------------------
    // CONSTRUCTORS
    // ----------------------------------

    public MyDbHelper(Context context) {
        super(context, DATABASE_FILE_NAME, null, context.getFilesDir().getAbsolutePath(), DATABASE_VERSION);
    }

}

Each time you will call getWritableDatabase() from your MyDbHelper instance, it will do all the copy/open stuff for you and return the writable database.

As I said before, I did not implement the upgrade() method in this sample, you'll have to. I also didn't implement getReadableDatabase() since I usually only use getWritableDatabase(). You may need to do it.

If you want to test it, just do the following:

  • Copy the code above
  • Create a folder in your assets called "databases" and insert your sqlite database file in it
  • In MyDatabaseHelper, change the value of the DATABASE_FILE_NAME constants with the name of the database in the asset folder
  • Don't forget to instantiate the MyDatabaseHelper and call for getWritableDatabse()

Hope this helped.

madyx
  • 119
  • 1
  • 6