How to pre populate database in Android using SQLite Database
Often, there is a need to initiate an Android app with an already existing database. This is called prepopulating a database. In this article, we will see how to pre-populate database in Android using SQLite Database. The database used in this example can be downloaded as Demo Database.
Approach:
- Add the support Library in build.gradle file and add Recycler View dependency in the dependencies section.
dependencies{implementation 'androidx.recyclerview:recyclerview:1.1.0'} - Make sure you add the database in assets folder. To create assets folder right click on app directory->new->Folder->(select)Assets Folder. Then simply paste your .db file in assets folder.
- In activity_main.xml, add the following code.
<?xmlversion="1.0"encoding="utf-8"?><LinearLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:paddingStart="5dp"android:paddingTop="5dp"><androidx.recyclerview.widget.RecyclerViewandroid:id="@+id/my_recycler_view"android:layout_width="match_parent"android:layout_height="match_parent"android:scrollbars="vertical"/></LinearLayout> - Create a new custom_layout.xml file with the following code.
<?xmlversion="1.0"encoding="utf-8"?><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="3dp"><TextViewandroid:textStyle="bold"android:layout_margin="5dp"android:textSize="20sp"android:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/textView"/></LinearLayout> - Create a DatabaseHelper class and add the following code.
packageorg.geeksforgeeks.dictionary;importandroid.app.Activity;importandroid.content.Context;importandroid.database.Cursor;importandroid.database.sqlite.SQLiteDatabase;importandroid.database.sqlite.SQLiteException;importandroid.database.sqlite.SQLiteOpenHelper;importandroid.util.Log;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;importjava.sql.SQLException;importjava.util.ArrayList;importjava.util.List;publicclassDatabaseHelperextendsSQLiteOpenHelper {// The Android's default system path// of your application database.privatestaticString DB_PATH ="";privatestaticString DB_NAME ="database.db";privateSQLiteDatabase myDataBase;privatefinalContext myContext;privateSQLiteOpenHelper sqLiteOpenHelper;// Table name in the database.publicstaticfinalStringALGO_TOPICS="algo_topics";/*** Constructor* Takes and keeps a reference of* the passed context in order* to access the application assets and resources. */publicDatabaseHelper(Context context){super(context, DB_NAME,null,1);this.myContext = context;DB_PATH = myContext.getDatabasePath(DB_NAME).toString();}// Creates an empty database// on the system and rewrites it// with your own database.publicvoidcreateDataBase()throwsIOException{booleandbExist = checkDataBase();if(dbExist) {// do nothing - database already exist}else{// By calling this method and// the empty database will be// created into the default system// path of your application// so we are gonna be able// to overwrite that database// with our database.this.getWritableDatabase();try{copyDataBase();}catch(IOException e) {thrownewError("Error copying database");}}}// Check if the database already exist// to avoid re-copying the file each// time you open the application// return true if it exists// false if it doesn't.privatebooleancheckDataBase(){SQLiteDatabase checkDB =null;try{String myPath = DB_PATH;checkDB= SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READONLY);}catch(SQLiteException e) {// database doesn't exist yet.Log.e("message",""+ e);}if(checkDB !=null) {checkDB.close();}returncheckDB !=null;}/*** Copies your database from your* local assets-folder to the just* created empty database in the* system folder, from where it* can be accessed and handled.* This is done by transferring bytestream.* */privatevoidcopyDataBase()throwsIOException{// Open your local db as the input streamInputStream myInput= myContext.getAssets().open(DB_NAME);// Path to the just created empty dbString outFileName = DB_PATH;// Open the empty db as the output streamOutputStream myOutput=newFileOutputStream(outFileName);// transfer bytes from the// inputfile to the outputfilebyte[] buffer =newbyte[1024];intlength;while((length = myInput.read(buffer)) >0) {myOutput.write(buffer,0, length);}// Close the streamsmyOutput.flush();myOutput.close();myInput.close();}publicvoidopenDataBase()throwsSQLException{// Open the databaseString myPath = DB_PATH;myDataBase = SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READONLY);}@Overridepublicsynchronizedvoidclose(){// close the database.if(myDataBase !=null)myDataBase.close();super.close();}@OverridepublicvoidonCreate(SQLiteDatabase db){// It is an abstract method// but we define our own method here.}@OverridepublicvoidonUpgrade(SQLiteDatabase db,intoldVersion,intnewVersion){// It is an abstract method which is// used to perform different task// based on the version of database.}// This method is used to get the// algorithm topics from the database.publicList<String> getAlgorithmTopics(Activity activity){sqLiteOpenHelper=newDatabaseHelper(activity);SQLiteDatabase db= sqLiteOpenHelper.getWritableDatabase();List<String> list=newArrayList<>();// query help us to return all data// the present in the ALGO_TOPICS table.String query ="SELECT * FROM "+ ALGO_TOPICS;Cursor cursor = db.rawQuery(query,null);if(cursor.moveToFirst()) {do{list.add(cursor.getString(1));}while(cursor.moveToNext());}returnlist;}} - Create a MyAdapter.java class and add the following code.
packageorg.geeksforgeeks.dictionary;importandroid.app.Activity;importandroid.view.LayoutInflater;importandroid.view.View;importandroid.view.ViewGroup;importandroid.widget.TextView;importandroidx.annotation.NonNull;importandroidx.recyclerview.widget.RecyclerView;importjava.util.List;publicclassMyAdapterextendsRecyclerView.Adapter<MyAdapter.ViewHolder> {privateList<String> data;Activity activity;publicMyAdapter(Activity activity,List<String> data){this.data = data;this.activity = activity;}// This method is used to attach// custom layout to the recycler view@NonNull@OverridepublicViewHolder onCreateViewHolder(@NonNullViewGroup parent,intviewType){LayoutInflater LI= activity.getLayoutInflater();View vw = LI.inflate(R.layout.custom_layout,null);returnnewViewHolder(vw);}// This method is used to set the action// to the widgets of our custom layout.@OverridepublicvoidonBindViewHolder(@NonNullViewHolder holder,intposition){holder.topic_name.setText(data.get(position));}@OverridepublicintgetItemCount(){returndata.size();}classViewHolderextendsRecyclerView.ViewHolder {TextView topic_name;publicViewHolder(View itemView){super(itemView);this.topic_name= itemView.findViewById(R.id.textView);}}} - Finally, in MainActivity.java add the following code.
packageorg.geeksforgeeks.algorithmTopics;importandroidx.appcompat.app.AppCompatActivity;importandroidx.recyclerview.widget.DefaultItemAnimator;importandroidx.recyclerview.widget.LinearLayoutManager;importandroidx.recyclerview.widget.RecyclerView;importandroid.os.Bundle;importjava.util.ArrayList;importjava.util.List;publicclassMainActivityextendsAppCompatActivity {privatestaticRecyclerView.Adapter adapter;privatestaticRecyclerView recyclerView;publicstaticList<String> data;DatabaseHelper db;@OverrideprotectedvoidonCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);recyclerView= findViewById(R.id.my_recycler_view);db =newDatabaseHelper(this);recyclerView.setLayoutManager(newLinearLayoutManager(this));data =newArrayList<>();fetchData();}publicvoidfetchData(){// Before fetching the data// directly from the database.// first we have to creates an empty// database on the system and// rewrites it with your own database.// Then we have to open the// database to fetch the data from it.db =newDatabaseHelper(this);try{db.createDataBase();db.openDataBase();}catch(Exception e) {e.printStackTrace();}data = db.getAlgorithmTopics(this);adapter =newMyAdapter(this, data);recyclerView.setAdapter(adapter);}}




