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

Source: Internet
Author: User
Tags sqlite

Assume that you use the default system administration, which is placed by default under packages. More worry. and will not cause data residue after uninstalling the app. But there is also a problem. For example, 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. Do not put it below the package and put it on the SD card.

Look carefully. Really not easy to do, online someone even to change the source code. But finally, the solution was found:

View Sqliteopenhelper source code. You will find a code like this:

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

Can see, when mname is not empty. 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 over. This mcontext realization:

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); /** * Get the database path, if not present, create object Object * @param name * @param mode * @param FA Ctory */@Override public File Getdatabasepath (String name) {//infer if there is an SD card bool            Ean sdexist = android.os.Environment.MEDIA_MOUNTED.equals (Android.os.Environment.getExternalStorageState ()); if (!sdexist) {//assumes not present, LOG.E ("SD card management:", "SD card does not exist. Please downloadInto the SD card ");            return null; } else{//assumes the existence//get SD card path String Dbdir=android.os.environment.getexternalstoragedi                Rectory (). toString ();                Dbdir + = "/scexam";//Database folder String DbPath = dbdir+ "/" +name;//database path//inferred folder exists, does not exist create the folder                File Dirfile = new file (Dbdir);                                if (!dirfile.exists ()) dirfile.mkdirs ();                 Whether the database file was created successfully boolean isfilecreatesuccess = false;                Infers whether the file exists, does not exist, 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.         This method is called by Android 2.3 and below.  * * @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, Databaseerr Orhandler ErrorHandler) {sqlitedatabase result = Sqlitedatabase.openorcreatedatabase (Getdatabasepath (name), Nu            ll);        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>


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.