Zils
Zils

Reputation: 405

How to move prebuilt android SQLite database to internal memory?

I'm using text file to generate SQLite database. My file is large so conversion taking so much time. I'm thinking if its possible to use pre-built database.

My database generated from TEXT file are saving on /data/data/com.my.project/database folder of internal memory.

Is there any way, I put Pre-built database on apk to bypass TEXT > SQLite conversion & directly copy existing db to /data/data/com.my.project/database folder during installation?? [N.B# My SQlite size is 30 MB ]

Upvotes: 2

Views: 645

Answers (1)

Merlevede
Merlevede

Reputation: 8170

Yes you can. You can save your database (your .db file) as an asset in your project file, and then, at runtime, check if the database exists, and if it doesn't you copy it from the assets.

Some of the code I use (you need to modify it according to your needs):

public static String getDBPath(Context c)
{
    return Environment.getDataDirectory() + 
              File.separator + "data" + 
              File.separator + c.getPackageName() + 
              File.separator + "databases";
}

public static String getDBFileName(Context c)
{
    return Environment.getDataDirectory() + 
              File.separator + "data" + 
              File.separator + c.getPackageName() + 
              File.separator + "databases" + 
              File.separator + "mydatabase.db;
}

public static void createCopyOfDatabaseIfNeeded(Context c) throws FileNotFoundException, IOException
{
    String preloadedDatabase = "preloaded/mydatabase.db";
    File dbdir = new File(myDB.getDBPath(c));
    if (!dbdir.exists())
        dbdir.mkdirs();
    File db = new File(myDB.getDBFileName(c));
    if (!db.exists())
    {
        // copy file from preloadedDatabase to db;
    }
}

Upvotes: 2

Related Questions