Importing Database in Android Studio

Introduction

 
This article will tell you how to import an existing database in Android.
 
I had a database named "Banking", that I wanted to use in another project. So we will import this database and make a copy of this database in our project. We will use a database file from the asset folder and copy it to the system database path of your application. 
 
Step 1
 
Pull the database file first. Go to "Monitor (DDMS included)" -> "File Explorer" -> "Data" -> "Data" then select the project from which you want to import the database (a project whose database you want to use in some other project) then select "Pull a file from device" (on top right corner) then select "Save the file".
 
 
Step 2
 
Create a new project.
 
Open "your_project_name.iml" and read the line <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
 
Now open your project folder. Go to "src" -> "main". Create a folder named assets. Place the database file that you saved in step 1 (Banking in this case) here.
 
Step 3
 
"strings.xml" used in this project is:
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.   <string name="app_name">DBImportFin</string>  
  4.   <string name="action_settings">Settings</string>  
  5.   <string name="hello_world">Welcome to import database...</string>  
  6. </resources> 
Step 4
 
Open the "activity_main.xml" layout file and add the following code to it:
  1. <TextView  
  2.            android:layout_width="wrap_content"  
  3.            android:layout_height="wrap_content"  
  4.            android:text="@string/hello_world"  
  5.            android:id="@+id/txt"/> 
The layout looks like:
 
im1.jpg
 
Step 5
 
Right-click on your project package then select "New" -> "Java class". Name this file "DBMain" and add the following code to it:
  1. package com.example.dbimportfin;  
  2.    
  3. import android.content.Context;  
  4. import android.database.Cursor;  
  5. import android.database.SQLException;  
  6. import android.database.sqlite.SQLiteDatabase;  
  7. import android.database.sqlite.SQLiteException;  
  8. import android.database.sqlite.SQLiteOpenHelper;  
  9. import android.util.Log;  
  10. import java.io.FileOutputStream;  
  11. import java.io.IOException;  
  12. import java.io.InputStream;  
  13. import java.io.OutputStream;  
  14.    
  15. public class DBMain extends SQLiteOpenHelper {  
  16.     private static String DB_PATH= "data/data/com.example.dbimportfin/databases/";  
  17.     private static String DB_NAME = "Banking";  
  18.     private SQLiteDatabase dbObj;  
  19.     private final Context context;  
  20.    
  21.     public DBMain(Context context) {  
  22.         super(context,  DB_NAME , null3);  
  23.         this. context  = context;  
  24.     }  
  25.    
  26.     public void createDB() throws IOException {  
  27.    
  28.             this.getReadableDatabase();  
  29.             Log.i("Readable ends....................","end");  
  30.    
  31.             try {  
  32.                 copyDB();  
  33.                 Log.i("copy db ends....................","end");  
  34.    
  35.             } catch (IOException e) {  
  36.    
  37.                 throw new Error("Error copying database");  
  38.         }  
  39.     }  
  40.    
  41.     private boolean checkDB(){  
  42.    
  43.         SQLiteDatabase checkDB = null;  
  44.    
  45.         try{  
  46.             String path = DB_PATH + DB_NAME;  
  47.             Log.i("myPath ......",path);  
  48.             checkDB = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);  
  49.    
  50.             Log.i("myPath ......",path);  
  51.             if (checkDB!=null)  
  52.             {  
  53.                 Cursor c= checkDB.rawQuery("SELECT * FROM bank"null);  
  54.                 Log.i("Cursor.......",c.getString(0));  
  55.                 c.moveToFirst();  
  56.                 String contents[]=new String[80];  
  57.                 int flag=0;  
  58.    
  59.                 while(! c.isAfterLast())  
  60.                 {  
  61.                     String temp="";  
  62.                     String s2=c.getString(0);  
  63.                     String s3=c.getString(1);  
  64.                     String s4=c.getString(2);  
  65.                     temp=temp+"\n Id:"+s2+"\tType:"+s3+"\tBal:"+s4;  
  66.                     contents[flag]=temp;  
  67.                     flag=flag+1;  
  68.                     
  69.                     Log.i("DB values.........",temp);  
  70.                     c.moveToNext();  
  71.    
  72.                 }  
  73.             }  
  74.                else  
  75.             {  
  76.                 return false;  
  77.             }  
  78.    
  79.         }catch(SQLiteException e){  
  80.             e.printStackTrace();  
  81.         }  
  82.    
  83.         if(checkDB != null){  
  84.    
  85.             checkDB.close();  
  86.    
  87.         }  
  88.         return checkDB != null ? true : false;  
  89.     }  
  90.    
  91.     public void copyDB() throws IOException{  
  92.         try {  
  93.             Log.i("inside copyDB....................","start");  
  94.    
  95.             InputStream ip =  context.getAssets().open(DB_NAME+".db");  
  96.             Log.i("Input Stream....",ip+"");  
  97.             String op=  DB_PATH  +  DB_NAME ;  
  98.             OutputStream output = new FileOutputStream( op);  
  99.             byte[] buffer = new byte[1024];  
  100.             int length;  
  101.             while ((length = ip.read(buffer))>0){  
  102.                 output.write(buffer, 0, length);  
  103.                 Log.i("Content.... ",length+"");  
  104.             }  
  105.             output.flush();  
  106.             output.close();  
  107.             ip.close();  
  108.         }  
  109.         catch (IOException e) {  
  110.             Log.v("error", e.toString());  
  111.         }  
  112.     }  
  113.    
  114.     public void openDB() throws SQLException {  
  115.    
  116.         String myPath = DB_PATH + DB_NAME;  
  117.         dbObj = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);  
  118.         Log.i("open DB......",dbObj.toString());  
  119.     }  
  120.    
  121.     @Override  
  122.     public synchronized void close() {  
  123.    
  124.         if(dbObj != null)  
  125.             dbObj.close();  
  126.    
  127.         super.close();  
  128.     }  
  129.    
  130.     @Override  
  131.     public void onCreate(SQLiteDatabase db) {  
  132.    
  133.     }  
  134.    
  135.     @Override  
  136.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  137.    
  138.     }  
The variable DB_PATH stores the path of the databases, in other words "Data" -> "Data" -> your project package -> "databases" -> name of your database.
 
The variable DB_NAME stores the name of your database (Banking in this case).
 
In createDB, "getReadableDatabases" will create an empty database in the default system path of your application. We will overwrite this database with our database.
 
In copyDB, context.getAssets().open(DB_NAME+".db") will get the "Banking" database file from the asset folder that we created in Step 2.
 
Step 6
 
Open "MainActivity" and add the following code to it:
  1. package com.example.dbimportfin;  
  2.    
  3. import android.content.Context;  
  4. import android.database.Cursor;  
  5. import android.database.SQLException;  
  6. import android.database.sqlite.SQLiteDatabase;  
  7. import android.os.Bundle;  
  8. import android.app.Activity;  
  9. import android.view.Menu;  
  10. import android.widget.TextView;  
  11. import java.io.IOException;  
  12.    
  13. public class MainActivity extends Activity {  
  14.    
  15.     String DB_PATH;  
  16.     final Context context=this;  
  17.     private SQLiteDatabase mDataBase;  
  18.     private static String DB_NAME ="Banking.db";  
  19.     TextView txt;  
  20.    
  21.     @Override  
  22.     protected void onCreate(Bundle savedInstanceState) {  
  23.         super.onCreate(savedInstanceState);  
  24.         setContentView(R.layout.activity_main);  
  25.    
  26.         txt=(TextView)findViewById(R.id.txt);  
  27.    
  28.         DBMain db;  
  29.         db = new DBMain(this);  
  30.    
  31.         try {  
  32.    
  33.              db.createDB();  
  34.         } catch (IOException ioe) {  
  35.    
  36.             throw new Error("Database not created....");  
  37.         }  
  38.    
  39.         try {   
  40.             db.openDB();  
  41.    
  42.         }catch(SQLException sqle){  
  43.    
  44.             throw sqle;  
  45.         }  
  46.    
  47.         SQLiteDatabase db1;  
  48.         db1=openOrCreateDatabase("Banking",SQLiteDatabase.CREATE_IF_NECESSARY,null);  
  49.         Cursor c= db1.rawQuery("SELECT * FROM bank",null);  
  50.    
  51.         c.moveToFirst();  
  52.    
  53.         String temp="";  
  54.         while(! c.isAfterLast())  
  55.         {  
  56.             String s2=c.getString(0);  
  57.             String s3=c.getString(1);  
  58.             String s4=c.getString(2);  
  59.             temp=temp+"\n Id:"+s2+"\tType:"+s3+"\tBal:"+s4;  
  60.             
  61.             c.moveToNext();  
  62.         }  
  63.         txt.setText(temp);  
  64.     }  
  65.    
  66.     @Override  
  67.     public boolean onCreateOptionsMenu(Menu menu) {  
  68.         // Inflate the menu; this adds items to the action bar if it is present.  
  69.         getMenuInflater().inflate(R.menu.main, menu);  
  70.         return true;  
  71.     }  
  72.  
Note that in the end, we are displaying the copied database.
 
Output snapshots:
 
im3.jpg
 
Thank you... Enjoy coding :)