In this tutorial you will learn, how can you read SQLite Database from assets folder? Sometimes you have a SQLite database file and want to read in your app. So this tutorial explain you about it.
In this example we need a .sqlite file and we put this file inside assets folder. Now let's start this example
Create activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/readTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
Add mydb.sqlite file inside assets folder.
Create model class Contact.java file
package com.valueinbrief.assetsdataexample;
public class Contact {
public int id;
public String name = "";
public String hint = "";
public Contact(int id, String name, String hint) {
this.id = id;
this.name = name;
this.hint = hint;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHint() {
return hint;
}
public void setHint(String hint) {
this.hint = hint;
}
}
Create SQLite database helper class SqlLiteDbHelper.java file
package com.valueinbrief.assetsdataexample;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.ArrayList;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 {private static final int DATABASE_VERSION = 1;private static final String DATABASE_NAME = "mydb.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;}public ArrayList<Contact> getDetails() {SQLiteDatabase db = this.getReadableDatabase();ArrayList<Contact> contList = new ArrayList<>();Cursor cursor = db.rawQuery("SELECT * FROM demo", null);if (cursor != null) {while (cursor.moveToNext()) {Contact cont = new Contact(cursor.getInt(0), cursor.getString(1), cursor.getString(2));contList.add(cont);}cursor.close();db.close();}return contList;}public void CopyDataBaseFromAsset() throws IOException {InputStream myInput = ctx.getAssets().open(DATABASE_NAME);// Path to the just created empty dbString outFileName = getDatabasePath();// if the path doesn't exist first, create itFile f = new File(ctx.getApplicationInfo().dataDir + DB_PATH_SUFFIX);if (!f.exists())f.mkdir();// 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();}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);}@Overridepublic void onCreate(SQLiteDatabase db) {}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}}
Create MainActivity.java file to retrieve data from Database
package com.valueinbrief.assetsdataexample;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.TextView;import java.util.ArrayList;public class MainActivity extends AppCompatActivity {TextView readTV;SqlLiteDbHelper dbHelper;ArrayList<Contact> contList;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);readTV = (TextView) findViewById(R.id.readTV);contList = new ArrayList<>();contList.clear();dbHelper = new SqlLiteDbHelper(this);dbHelper.openDataBase();contList = dbHelper.getDetails();String msg ="";for(int i=0;i<contList.size();i++){Contact cont = contList.get(i);msg = msg+cont.getId()+" "+cont.getName()+" "+cont.getHint()+"\n\n\n";readTV.setText(msg);}}}
If you want to get new posts, make sure to subscribe to Value In Brief by Email.