When the Android Application creates a database, it is established in the system by default/data/'application package name '/
Sometimes we need to build it in the SD card.
Advantages of SD card:
1. After the system restores the factory settings, reinstall the application. Data will not be lost.
2. Convenient backup and recovery. You only need to copy data to the PC or the SD card of the Android device from the PC.
And so on.
How can we easily move the database to the SD card?
1 initialization, SD card path. Define the path of the database.
Package CN. HPC. dbdemo; import Java. io. file; import android. OS. environment; /** the database root directory/sdcard/hpcdbdata/Application Data is created in/sdcard/hpcdbdata/'package name'/*/public class sdbhelper {public static final string db_dir = environment. getexternalstoragedirectory (). getpath () + file. separator + "hpcdbdata" + file. separator + sdbhelper. class. getpackage (). getname (); static {While (! Environment. getexternalstoragestate (). equals (environment. media_mounted) {try {thread. sleep (500);} catch (interruptedexception e) {e. printstacktrace (); break;} file dbfolder = new file (db_dir); // If (! Dbfolder. exists () {dbfolder. mkdirs ();}}}
2. Use sqliteopenhelper.
Mdbname: database name with full path
Package CN. HPC. dbdemo; import android. content. context; import android. database. SQLite. sqlitedatabase; import android. database. SQLite. sqlitedatabase. cursorfactory; import android. database. SQLite. sqliteopenhelper; public class demodbh extends sqliteopenhelper {public static final int version = 1; public static final string mdbname = sdbhelper. db_dir + file. separator + "demo. DB "; Public demodbh (context) {super (context, mdbname, null, version );}//... others are omitted to reduce layout occupation}
Very simple.
Finished