Как предварительно заполнить базу данных в Android с помощью базы данных SQLite
Опубликовано: 4 Января, 2022
Часто возникает необходимость запустить приложение Android с уже существующей базой данных. Это называется предварительным заполнением базы данных . В этой статье мы увидим, как предварительно заполнить базу данных в Android с помощью базы данных SQLite. База данных, используемая в этом примере, может быть загружена как демонстрационная база данных.
Подход:
- Добавьте библиотеку поддержки в файл build.gradle и добавьте зависимость Recycler View в раздел зависимостей.
dependencies{implementation 'androidx.recyclerview:recyclerview:1.1.0'} - Убедитесь, что вы добавили базу данных в папку с ресурсами. Чтобы создать папку с активами, щелкните правой кнопкой мыши каталог приложения-> новая-> Папка -> (выберите) Папку с активами . Затем просто вставьте файл .db в папку с ресурсами.
- В activity_main.xml добавьте следующий код.
<?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> - Создайте новый файл custom_layout.xml со следующим кодом.
<?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> - Создайте класс DatabaseHelper и добавьте следующий код.
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());}list;return}} - Создайте класс MyAdapter.java и добавьте следующий код.
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,position)int{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);}}} - Наконец, в MainActivity.java добавьте следующий код.
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);}}
Выход:
Вниманию читателя! Не прекращайте учиться сейчас. Получите все важные концепции теории CS для собеседований SDE с курсом теории CS по доступной для студентов цене и будьте готовы к отрасли.