Method of writing SD card to Android database SQLite

  • 2021-06-28 14:07:48
  • OfStack

If the mobile phone does not have root, the database file is not visible and is not easy to debug.

The best way is to write the database into the SD card.

There are two changes:

1. Put the database file name DATABASE_in your helper classNAME changes from the original file name to a path.

Before modification: DATABASE_NAME = "demo.db"


public class MyDBHelper extends SQLiteOpenHelper {
public static final int VERSION = 1; // Database Version Number 
public static final String DATABASE_NAME = "demo.db"; // Database Name 
public static final String TABLE_NAME = "mytag"; // Data table name, 1 A database can contain multiple tables, similar to excel In sheet1 , sheet2
//MyDBHelper  Constructor, we care about names DATABASE_NAME And version VERSION
public MyDBHelper(Context context) {
super(context, DATABASE_NAME, null, VERSION);
}

Modified: DATABASE_NAME ='/mnt/sdcard/demo.db'


public class MyDBHelper extends SQLiteOpenHelper {
public static final int VERSION = 1; // Database Version Number 
public static final String DATABASE_NAME = "/mnt/sdcard/demo.db"; // Database Name 
public static final String TABLE_NAME = "mytag"; // Data table name, 1 A database can contain multiple tables, similar to excel In sheet1 , sheet2
//MyDBHelper  Constructor, we care about names DATABASE_NAME And version VERSION
public MyDBHelper(Context context) {
super(context, DATABASE_NAME, null, VERSION);
}

Because if there is only a single file name, the last database file created is stored in the / data / data / Package Name / databases directory of the internal memory card (either the running memory or the SD card) of the phone, and this / data root folder cannot be accessed without the root phone, nor can it be opened in the adb shell mode.

2.Finally, don't forget to modify permissions!

The Android mobile phone has strict security control. The SD card belongs to the external memory. Accessing the files above requires adding permissions.

Add two SD card read and write permissions to AndroidManifest.xml:


<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 

If no permissions are added, the program terminates abnormally.

The above is the method of writing SD card for Android database SQLite, and I hope it will be helpful for you!


Related articles: