Updated 8 March 2019
In this blog, I am going to show you how to ship your default database with your application.
So let’s Begin!!
When you have an Android app that has a built-in database. The more Cleared way, you have pre-created the SQLite database and include it in the APK. Whenever your application runs it uses the same database which you have included in it.
There are some easy steps for shipping your application with a built-in database.
Step 1: Create your database and create tables that you want to be in the application by default. And then export it using any DB browser or you can do it manually.
Step 2: Copy your .db file in your assets folder,
Step 3: Copy your database file from assets folder to your android database location,
123456789101112131415161718192021222324 public static String DB_PATH = "/data/data/" + BuildConfig.APPLICATION_ID + "/databases/";public static String DB_NAME = "db_pos.db";public static void setDefaultDataBase(Context context) {try {InputStream myInput = context.getAssets().open(DB_NAME);// Path to the just created empty dbString outFileName = DB_PATH + DB_NAME;//Open the empty db as the output streamOutputStream myOutput = new FileOutputStream(outFileName);//transfer bytes from the inputfile to the outputfilebyte[] buffer = new byte[1024];int length;while ((length = myInput.read(buffer)) > 0) {myOutput.write(buffer, 0, length);}//Close the streamsmyOutput.flush();myOutput.close();myInput.close();} catch (IOException e) {e.printStackTrace();}}
Step 4: Checking is database already exist or not,
123456789101112131415161718192021 private boolean checkDataBase() {Log.d(TAG, "checkDataBase: Enter");SQLiteDatabase checkDB = null;try {checkDB = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null,SQLiteDatabase.OPEN_READWRITE);checkDB.close();Log.d(TAG, "checkDataBase: loaded");} catch (SQLiteException e) {Log.d(TAG, "checkDataBase: SQLiteException---" + e);e.printStackTrace();Helper.setDefaultDataBase(this);AppSharedPref.setSignedUp(this, true);} catch (Exception e) {Log.d(TAG, "checkDataBase: Exception " + e);e.printStackTrace();Helper.setDefaultDataBase(this);AppSharedPref.setSignedUp(this, true);}return checkDB != null;}
If not exist put your preloaded db file in that. And create your app.
Bravo!!! You have successfully shipped your application with your default database.
Thanks for reading this Technical blog, I Hope this is helpful for you. If you got any query or issue please ask me on the comment below.
Stay updated and Stay Cool. 🙂
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.