Use Sqliteopenhelper to manage databases in an SD card in Android

Source: Internet
Author: User
Tags sqlite manager

The creation and management of the database can be done using the Sqliteopenhelper that comes with Android, with two limitations:

(1) The database is created in the memory card, the size is limited, the creation location is in the/data/data/application name/databases (can be viewed using Eclispe ddms).

(2) If you cannot get root permissions, you cannot view the created database directly.

In view of the above limitations and actual needs, it is intended to use Sqliteopenhelper to manage the database on the SD card, by studying the source code of the Sqliteopenhelper, and discovering that its creation or opening of the database is in the Getwritabledatabase () function ( The getreadabledatabase itself is also called getwritabledatabase):

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

Analysis of the above code found that when the database name is non-empty, the database is created or opened by Mcontext, this mcontext by the Sqliteopenhelper constructor passed in: Sqliteopenhelper (context context, String name, Sqlitedatabase.cursorfactory factory, int version). Then we overload its openorcreatedatabase function for the incoming context, so that it can complete our goal by creating the database into the SD card.

The corresponding Sqliteopenhelper implementation class Sdcarddbhelper

Import Android.content.context;import Android.database.sqlexception;import Android.database.sqlite.SQLiteDatabase ; Import android.database.sqlite.sqliteopenhelper;import android.util.log;/** * Database management and Maintenance classes **/public class    Sdcarddbhelper extends sqliteopenhelper{public static final String TAG = "Sdcarddbhelper";        /** * Database name **/public static String database_name = "SDDB.DB";            /** * Database version **/public static int database_version = 1; /** * Constructor * * @param context **/Public sdcarddbhelper (context context) {Super (context    , database_name, NULL, database_version); /** * Triggers when database is created, database tables required to create offline storage * * @param db **/@Override public void OnCreate (sqlit        Edatabase db) {LOG.E (TAG, "Start database table creation");  try{//Create User table Db.execsql ("CREATE table if not exists user" + "(_id integer Primary key Autoincrement,name varchar (a), password VarcHar (updatetime), role varchar (20));        LOG.E (TAG, "Create offline required database tables successfully");            } catch (SQLException se) {se.printstacktrace ();        LOG.E (TAG, "Create offline required database table failed");    }}/** triggered when updating the database, * * @param db * @param oldversion * @param newversion **/ @Override public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {//db.execsql ("ALTER tabl       E person ADD COLUMN and other STRING "); }}

Overloaded Openorcreatedatabase creates a context for the database on the SD card

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 load SD card");  return null;          } else{//if present//Get SD card path String Dbdir=android.os.environment.getexterna                Lstoragedirectory (). GetAbsolutePath ();                Dbdir + = "/database";//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 op            Enorcreatedatabase (String name, int mode, Cursorfactory factory, Databaseerrorhandler ErrorHandler) {            Sqlitedatabase result = Sqlitedatabase.openorcreatedatabase (Getdatabasepath (name), NULL);        return result;  }    }

Calling program:

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

In particular, it is worth noting that different versions of the Android API call different Openorcreatedatabase functions.

Of course, you can also directly use Sqlitedatabase to create the database on the SD card, or directly modify the Sqliteopenhelper source code recompile, but the former did not do some testing database fault-tolerant processing, Also less than Sqliteopenhelper to the database operation convenience. The latter is of great workload and is not recommended for use.

Finally, remember to add read and write access to the SD card:

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

SQLite Desktop Viewing Tools: SQLite Administrator, SQLite man or Firefox plugin SQLite manager.

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.