SoFunction
Updated on 2025-03-11

Android Database SQLite How to write to SD card

If the phone does not have root, the database file cannot be viewed, which is inconvenient to debug.

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

There are two places to modify:

1. Change the database file name DATABASE_NAME from the original file name to the path in your helper class.

Before modification: DATABASE_NAME = ""

public class MyDBHelper extends SQLiteOpenHelper {
public static final int VERSION = 1; //Database version numberpublic static final String DATABASE_NAME = ""; //Database namepublic static final String TABLE_NAME = "mytag"; //Data table name, a database can contain multiple data tables, similar to sheet1 and sheet2 in Excel//MyDBHelper constructor, we are concerned with the name DATABASE_NAME and the version VERSIONpublic MyDBHelper(Context context) {
super(context, DATABASE_NAME, null, VERSION);
}

After modification: DATABASE_NAME = "/mnt/sdcard/"

public class MyDBHelper extends SQLiteOpenHelper {
public static final int VERSION = 1; //Database version numberpublic static final String DATABASE_NAME = "/mnt/sdcard/"; //Database namepublic static final String TABLE_NAME = "mytag"; //Data table name, a database can contain multiple data tables, similar to sheet1 and sheet2 in Excel//MyDBHelper constructor, we are concerned with the name DATABASE_NAME and the version VERSIONpublic MyDBHelper(Context context) {
super(context, DATABASE_NAME, null, VERSION);
}

Because if it is just a separate file name, the database file created in the /data/data/package name/databases directory of the internal memory card of the mobile phone (not running memory or SD card). For mobile phones without root, this /data root folder cannot be entered and cannot be opened in the adb shell method.

2. Finally, don’t forget to modify the permissions!

Android phones have strict security controls. The SD card belongs to external memory. Accessing the above files requires adding permissions.

Add two SD card read and write permissions to:

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

If no permission is added, the program will terminate abnormally.

The above is a method for writing SD cards to the Android database SQLite. I hope it will be helpful to everyone!