Android external database in assets folder

Anas Shahid picture Anas Shahid · Jun 17, 2013 · Viewed 14.4k times · Source

I have an android application that is supposed to read and expand a database that is already created on sqlite...it works fine on emulator by putting database in "data/data/(packagename)/database" folder on the file explorer of emulator. Now problem is occuring with the real device. Obviously it doesnt have the database to open.I tried to put database in assets folder but I am not getting to open it with the openhelper.

Answer

Gva picture Gva · Jun 17, 2013

you should copy the .db file from your assets folder to an internal/external storage. You can use following codes,

private static String DB_PATH = "/data/data/your package/database/";  
private static String DB_NAME ="final.db";// Database name 

To create a database,

public void createDataBase() throws IOException 
{ 
  //If database not exists copy it from the assets 

   boolean mDataBaseExist = checkDataBase(); 
   if(!mDataBaseExist) 
   { 
      try  
      { 
        //Copy the database from assests 
        copyDataBase(); 
        Log.e(TAG, "createDatabase database created"); 
      }  
      catch (IOException mIOException)  
      { 
         throw new Error("ErrorCopyingDataBase"); 
     } 
  } 
} 

Check that the database exists here: /data/data/your package/database/DB Name

private boolean checkDataBase() 
{ 
    File dbFile = new File(DB_PATH + DB_NAME); 
    return dbFile.exists(); 
} 

Copy the database from assets

  private void copyDataBase() throws IOException 
  { 
    InputStream mInput = getApplicationContext().getAssets().open(DB_NAME); 
    String outFileName = DB_PATH + DB_NAME; 
    OutputStream mOutput = new FileOutputStream(outFileName); 
    byte[] mBuffer = new byte[1024]; 
    int mLength; 
    while ((mLength = mInput.read(mBuffer))>0) 
    { 
        mOutput.write(mBuffer, 0, mLength); 
    } 
    mOutput.flush(); 
    mOutput.close(); 
    mInput.close(); 
}

i hope it should help you.