Read and copy DataBase from Assets folder

In this blog post, I would like to explain how to read and copy your own Database in the Application.

First, create your own database. To do this, you need Mozilla firefox browser with SQLite Manager pulg-in addon.

Now open SQLite Manager and create new database option or simply select this icon  and type a database name.

Capture

Now create a new table or simply select this icon  and follow these screenshots.

Capture2

Capture3

 

Capture4

Capture5

Second, copy that database inside the assets folder.

Third, on MainActivity.java class, copy paste this code.


import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class MainActivity extends Activity {

SqlLiteDbHelper dbHelper;
Contact contacts ;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

dbHelper = new SqlLiteDbHelper(this);

dbHelper.openDataBase();
contacts = new Contact();
contacts = dbHelper.Get_ContactDetails();
TextView tv1 = (TextView)findViewById(R.id.textView1);

tv1.setText("Name: "+contacts.getName()+"\n Mobile No: "+contacts.getMobileNo());
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

Fourth, create a DataBase, copy paste this code.


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class SqlLiteDbHelper extends SQLiteOpenHelper {

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "database.sqlite";
private static final String DB_PATH_SUFFIX = "/databases/";
static Context ctx;
public SqlLiteDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
ctx = context;
}

// Getting single contact
public Contact Get_ContactDetails() {
SQLiteDatabase db = this.getReadableDatabase();

Cursor cursor = db.rawQuery("SELECT * FROM contact", null);
if (cursor != null && cursor.moveToFirst()){
Contact cont = new Contact(cursor.getInt(0),cursor.getString(1), cursor.getString(2));
// return contact
cursor.close();
db.close();

return cont;

}
return null;
}

public void CopyDataBaseFromAsset() throws IOException{

InputStream myInput = ctx.getAssets().open(DATABASE_NAME);

// Path to the just created empty db
String outFileName = getDatabasePath();

// if the path doesn't exist first, create it
File f = new File(ctx.getApplicationInfo().dataDir + DB_PATH_SUFFIX);
if (!f.exists())
f.mkdir();

// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);

// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}

// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();

}
private static String getDatabasePath() {
return ctx.getApplicationInfo().dataDir + DB_PATH_SUFFIX
+ DATABASE_NAME;
}

public SQLiteDatabase openDataBase() throws SQLException{
File dbFile = ctx.getDatabasePath(DATABASE_NAME);

if (!dbFile.exists()) {
try {
CopyDataBaseFromAsset();
System.out.println("Copying sucess from Assets folder");
} catch (IOException e) {
throw new RuntimeException("Error creating source database", e);
}
}

return SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.CREATE_IF_NECESSARY);
}

@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub

}
}

Fifth, create a contact.java class and copy paste this code.


public class Contact {

public int _id;
public String name = "";
public String mobileNo = "";

public int getID() {
return this._id;
}

public void setID(int id) {
// TODO Auto-generated method stub
this._id = id;
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public String getMobileNo() {
return mobileNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
// constructor
public Contact (int id, String name, String mobileNo){
this._id = id;
this.mobileNo = mobileNo;
this.name = name;
}

public Contact (){

}
}

Sixth, on your activity_main.xml file, copy paste this code.


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="net.sourcecodez.database_fromassetsfolder.MainActivity" >

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="77dp"
        android:text="Displaying data from DataBase"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

ScreenShots:

Screenshot_2014-10-01-18-10-20[1]
Download Source Code from here.

durga chiranjeevi

durga chiranjeevi

I'm currently working as Android developer at Energy Alternatives India. Interested in Application and Game development.
durga chiranjeevi
Comments
  1. Priyanka
  2. Manoj

Leave a Reply

Your email address will not be published. Required fields are marked *