Thursday 6 November 2014

HB Blog 33: How To Access Database From Asset Folder In Android.

In this post, I will show how to access sqlite database from asset folder in android.
We just need to create a new project and keep our desire sqlite databasein asset folder.Then, using simple code we will first copy the database into sd card  and you can use database as normally by firing queries.
Have a look on few code snippets,

DataBaseHelper.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
//Copies your database from your local assets-folder to the just created empty database in the system folder
    private void copyDataBase() throws IOException
    {
          String outFileName = DATABASE_PATH + DATABASE_NAME;
          OutputStream myOutput = new FileOutputStream(outFileName);
          InputStream myInput = myContext.getAssets().open(DATABASE_NAME);
          byte[] buffer = new byte[1024];
          int length;
          while ((length = myInput.read(buffer)) > 0){
                myOutput.write(buffer, 0, length);
          }
          myInput.close();
          myOutput.flush();
          myOutput.close();
    }

Refer the below link for complete sample code:-
Download Sample Code
Download Apk File

No comments:

Post a Comment