Android uses Sqlliteopenhelper to change the storage path of the database onto the SD card

Source: Internet
Author: User

If using the default system management, the default is placed under the package, more worry, and after uninstalling the app will not cause data residue, but this also has a problem, such as I do a back word software, then when the user uninstalled the app, he worked hard to download the word library also lost ...

So I think of the solution is to change the database path, not put under the package, put on the SD card. Look carefully, it is not easy to do, online someone even to change the source code. Finally, however, we found a solution:

Look at the Sqliteopenhelper source code, you will find that there is such a piece:

if (Mname = = null) {     db = Sqlitedatabase.create (null);     } else {     db = mcontext.openorcreatedatabase (mname, 0, M Factory);     }

You can see that when mname is not empty, it is created and opened by Mcontext. And this mcontext can be passed through the constructor function.

Look at the Sqlliteopenhelper this implementation class:

Package Cn.com.xx.xx.util;import Android.content.context;import Android.database.sqlite.sqlitedatabase;import android.database.sqlite.sqliteopenhelper;/** * Database Helper class  * @author Howlaa * @date 2015-1-5 14:38:28 */pub Lic class Dbopenhelper extends Sqliteopenhelper {private static final String DBNAME = "test.db";    private static final int VERSION = 11;public Dbopenhelper (context context) {Super (context, DBNAME, NULL, VERSION);//it ' s Location is data/data/pakage/database} @Overridepublic void OnCreate (Sqlitedatabase db) {//it'll be called when the Datab ASE is created first  db.execsql ("CREATE TABLE IF not EXISTS exam_type (ID integer primary key autoincrement, Type_nam e varchar (+), type_id INTEGER) "); } @Override  //It ' ll be called when the database is updatedpublic void Onupgrade (sqlitedatabase db, int oldversion, in T newversion) {}}

The rest is going to be done with this mcontext:

Package Cn.com.smartcost.scexam.util;import Java.io.file;import Java.io.ioexception;import android.content.Context ; Import Android.content.contextwrapper;import Android.database.databaseerrorhandler;import Android.database.sqlite.sqlitedatabase;import Android.database.sqlite.sqlitedatabase.cursorfactory;import                           android.util.log;/** * is used to support access to the database stored on the SD card **/public class Databasecontext extends Contextwrapper { /** * Constructor * @param base context */public databasecontext (context base) {Su        Per (base); /** * Gets the database path, if it does not exist, creates the object object * @param name * @param mode * @param FA Ctory */@Override public File Getdatabasepath (String name) {//To determine if there is an SD card bool            Ean sdexist = android.os.Environment.MEDIA_MOUNTED.equals (Android.os.Environment.getExternalStorageState ()); if (!sdexist) {//If not present, LOG.E ("SD card management:", "SD card does not exist, please addSD card ");            return null; } else{//if present//Get SD card path String Dbdir=android.os.environment.getexternalstoragedi                Rectory (). toString ();                Dbdir + = "/scexam";//the directory where the database is located String dbPath = dbdir+ "/" +name;//database path//Determine if the directory exists and does not exist then create the directory                File Dirfile = new file (Dbdir);                                if (!dirfile.exists ()) dirfile.mkdirs ();                 Whether the database file was created successfully boolean isfilecreatesuccess = false;                Determines whether the file exists, does not exist, and creates the file DBFile = new files (dbPath); if (!dbfile.exists ()) {try {isfilecreatesuccess = Dbfile.cre                         Atenewfile ();//Create File} catch (IOException e) {//TODO auto-generated catch block                    E.printstacktrace ();            }} else             Isfilecreatesuccess = true;                Returns the database file object if (isfilecreatesuccess) return dbfile;            else return null;         }}/** * Overloads this method, which is used to open the database on the SD card, Android 2.3 and the following will call this method.  * * @param name * @param mode * @param factory */@Override Public            Sqlitedatabase openorcreatedatabase (String name, int mode, Sqlitedatabase.cursorfactory Factory) {            Sqlitedatabase result = Sqlitedatabase.openorcreatedatabase (Getdatabasepath (name), NULL);        return result;         /** * Android 4.0 calls this method to get the database. * * @see android.content.contextwrapper#openorcreatedatabase (java.lang.String, int, * Andro Id.database.sqlite.SQLiteDatabase.CursorFactory, * android.database.DatabaseErrorHandler) * @ param NAME * @param mode * @param factory * @param errorhandler */@Override Public sqlitedatabase openorcreatedatabase (String name, int mode, Cursorfactory factory, Databaseerrorh Andler ErrorHandler) {sqlitedatabase result = Sqlitedatabase.openorcreatedatabase (Getdatabasepath (name), NULL)            ;        return result; }    }

Use:

Databasecontext dbContext = new Databasecontext (this); Sdcarddbhelper dbhelper = new Sdcarddbhelper (dbContext);

Finally, do not forget, plus read and write the SD card permissions:

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


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android uses Sqlliteopenhelper to change the storage path of the database onto the SD card

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.