Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import pre-made db to sqlite managed by ormlite

I have a .db file and I want to setup it at first run of my android application. I use OrmLite to manage my database.

In that .db file a have about 7000 records and when I want to import it by common methods (use foreach - create command ) it takes many time (about 2-3 mins) to import.

How can i solve this problem?

thanks

like image 494
Hossain Khademian Avatar asked Nov 10 '13 05:11

Hossain Khademian


Video Answer


1 Answers

Let say you have database named "prepared.db" and your package name is "com.example.android". This is what I do.

  1. make sure you prepared database is under assets folder.
  2. In the constructor of class that extends OrmLiteSqliteOpenHelper, check whether or not database exist.
  3. If database DID NOT exist, copy db from assets folder

(Both Step 2 and 3 happen inside constructor)

This is code sample and It work for me.

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {

    private static final String DATABASE_NAME = "prepared.db";
    private static final String DATABASE_PATH = "/data/data/com.example.android/databases/";


    public DatabaseHelper(Context context) {
        super(context, DATABASE_PATH+DATABASE_NAME, null, DATABASE_VERSION);

        boolean dbexist = checkdatabase();
        if (!dbexist) {

            // If database did not exist, try copying existing database from assets folder.
            try {
                File dir = new File(DATABASE_PATH);
                dir.mkdirs();
                InputStream myinput = mContext.getAssets().open(DATABASE_NAME);
                String outfilename = DATABASE_PATH + DATABASE_NAME;
                Log.i(DatabaseHelper.class.getName(), "DB Path : " + outfilename);
                OutputStream myoutput = new FileOutputStream(outfilename);
                byte[] buffer = new byte[1024];
                int length;
                while ((length = myinput.read(buffer)) > 0) {
                    myoutput.write(buffer, 0, length);
                }
                myoutput.flush();
                myoutput.close();
                myinput.close();            
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /*
    * Check whether or not database exist
    */
    private boolean checkdatabase() {
        boolean checkdb = false;

        String myPath = DATABASE_PATH + DATABASE_NAME;
        File dbfile = new File(myPath);
        checkdb = dbfile.exists();

        Log.i(DatabaseHelper.class.getName(), "DB Exist : " + checkdb);

        return checkdb;
    }
}

P.S : If the database file size is more than 1mb, error will occur. You can split database to solve such issue.

like image 128
Hein Avatar answered Sep 21 '22 14:09

Hein