How to save the database to SD card _android based on Android

Source: Internet
Author: User
Tags object object

Sometimes in order to need, the database will be saved to the external storage or SD card (for this situation can be encrypted data to prevent data from being cracked), such as an application to support multiple data, each data need to have a corresponding database, and the information in the database is particularly large, This is obviously more important to keep the database in an external storage or SD card, because the size of the RAM is limited, and second, it is easier to see the contents of the database in the SD card when writing certain test programs.

When Android creates a database through Sqliteopenhelper, the default is to save the database in the '/data/data/application name/ Databases ' directory, you just have to pass in the database name in the constructor of the inherited Sqliteopenhelper class, but if you save the database to the specified path, you need to override the context in the constructor of the Sqliteopenhelper class, because: Reading Sqliteopenhelper.java's source will be found: the creation of the database is through the context of the Openorcreatedatabase method, if we need to create a database under the specified path, we need to write a class to inherit the environment, and replication of its openorcre Atedatabase method, specify the path of the database store in the Openorcreatedatabase method, The following is the source code for the Getwritabledatabase and Getreadabledatabase methods in class Sqliteopenhelper, Sqliteopenhelper is to create the database through these two methods.

/** * Create and/or open a database that'll be used for reading and writing. * the ' the ' is called, the database would be opened and * {@link #onCreate}, {@link #onUpgrade} and/or {@link #
  OnOpen} would be * called. * * <p>once opened successfully, the database is cached, so can * call this method every time you need to WR
  ITE to the database.
  * (make sure to call {@link #close} when you no longer need the database.) * Errors such as bad permissions or a full disk could cause this method * to fail, but future-may attempts if the Problem is fixed.</p> * * <p class= "Caution" >database upgrade could take a long time, your * should not cal L This method is application main thread, including * from {@link android.content.contentprovider#oncreate content
  Provider.oncreate ()}. * * @throws Sqliteexception If the database cannot to opened for writing * @return a read/write database object valid Until {@link #close} is called
  */Public synchronized Sqlitedatabase getwritabledatabase () {if (mdatabase!= null) {if (!mdatabase.isopen ()) { darn!
   The user closed the database by calling Mdatabase.close () mdatabase = null; ' Else If ' (!mdatabase.isreadonly ()) {return mdatabase;//The ' database is already ' open for business}} if (MI
  sinitializing) {throw new IllegalStateException ("Getwritabledatabase called recursively"); }//If We have a read-only database open, someone could be using it//(though they shouldn ' t), which would cause a l Ock to is held on//the file, and we attempts to open the database read-write would//fail waiting for the file loc
  K. To prevent that, we acquire the "//Lock on" The Read-only database, which shuts out other users.
  Boolean success = false;
  Sqlitedatabase db = null;
  if (mdatabase!= null) mdatabase.lock ();
   try {misinitializing = true;
   if (Mname = = null) {db = Sqlitedatabase.create (null); else {db = MContext.openorcreatedatabase (mname, 0, MFactory, Merrorhandler);
   int version = Db.getversion ();
    if (version!= mnewversion) {db.begintransaction ();
     try {if (Version = = 0) {onCreate (db);
      else {if (Version > Mnewversion) {ondowngrade (db, version, mnewversion);
      else {onupgrade (db, version, mnewversion);
     } db.setversion (Mnewversion);
    Db.settransactionsuccessful ();
    finally {db.endtransaction ();
   } onOpen (db);
   Success = true;
  return DB;
   finally {misinitializing = false; if (success) {if (mdatabase!= null) {try {mdatabase.close ();} catch (Exception e) {} mdatabase.unlock (
    );
   } mdatabase = db;
    else {if (mdatabase!= null) mdatabase.unlock ();
   if (db!= null) db.close (); }}/** * Create and/or open a database. This is the same object returned by * {@link #getWritableDatabase} unless some problem, suchAs a full disk, * requires the database to be opened read-only. In the case, a read-only * database object would be returned. If the problem is fixed, a future call * to {@link #getWritableDatabase} may succeed, in which case the read-only * da
  Tabase object would be closed and the Read/write object would be returned * the future. * * <p class= "Caution" >like {@link #getWritableDatabase}, this is may * take a long  Hould not call it from the * application main thread, including from * {@link android.content.contentprovider#oncreate
  Contentprovider.oncreate ()}. * * @throws Sqliteexception If the database cannot be opened * @return a database object valid until {@link #getWritab
  Ledatabase} * or {@link #close} is called.
    */Public synchronized Sqlitedatabase getreadabledatabase () {if (mdatabase!= null) {if (!mdatabase.isopen ()) { darn! The user closed the database by calling Mdatabase.close () Mdatabase = nulL  else {return mdatabase;//The ' database is already ' open for business}} if (misinitializing) {throw new
  IllegalStateException ("Getreadabledatabase called recursively");
  try {return getwritabledatabase ();
   catch (Sqliteexception e) {if (mname = = null) throw e;//Can ' t open a temp database read-only!
  LOG.E (TAG, "couldn ' t open" + Mname + "for writing ('ll try Read-only):", e);
  } sqlitedatabase db = null;
   try {misinitializing = true;
   String path = Mcontext.getdatabasepath (Mname). GetPath ();
   db = Sqlitedatabase.opendatabase (path, mfactory, sqlitedatabase.open_readonly, Merrorhandler);
      if (Db.getversion ()!= mnewversion) {throw new Sqliteexception ("Can ' t upgrade read-only database from version" +
   Db.getversion () + "to" + Mnewversion + ":" + path);
   } onOpen (db);
   LOG.W (TAG, "opened" + Mname + "in read-only mode");
   Mdatabase = db;
  return mdatabase;
  finally {misinitializing = false; if (db!= null && db!= mdatabase) db.close (); }
 }

Through the analysis above, you can write a custom context class that inherits the context, but because there are other abstract functions besides the Openorcreatedatabase method, Therefore, it is recommended to use Non-abstract class Contextwrapper, which inherits from the context, and the custom Databasecontext class source code is as follows:

public class Databasecontext extends Contextwrapper {public Databasecontext (context) {super); /** * Obtains the database path and, if not, creates object Object * @param name * @param mode * @param factory * * @Override public File Getdataba Sepath (String name) {//To determine whether there is an SD card Boolean sdexist = Android.os.Environment.MEDIA_MOUNTED.equals (android.os.Environmen
  T.getexternalstoragestate ());
  if (!sdexist) {//If not present, return null;
   }else{//if present//Get SD card path String dbdir= Fileutils.getflashbpath (); Dbdir + = "DB";//Database directory String DBPath = dbdir+ "/" +name;//database path//Decision directory exists, does not exist then create the directory file Dirfile = new file (dbdir
   );
   if (!dirfile.exists ()) {dirfile.mkdirs (); 
   ///Database file creation succeeded Boolean isfilecreatesuccess = false;
   To determine if a file exists and does not exist, create the file DBFile = new filename (dbpath);
     if (!dbfile.exists ()) {try {isfilecreatesuccess = Dbfile.createnewfile ();//Create File} catch (IOException e) {
    E.printstacktrace ();
}}else{isfilecreatesuccess = true;   //Returns the database file object if (isfilecreatesuccess) {return dbfile;
   }else{return null;
  The/** * Overload method is used to open the database on the SD card, and this method is called by Android 2.3 and below. * * @param name * @param mode * @param factory/@Override public sqlitedatabase openorcreatedatabase (String n AME, int mode, Sqlitedatabase.cursorfactory Factory) {sqlitedatabase result = Sqlitedatabase.openorcreatedatabase (GetD
  Atabasepath (name), NULL);
 return result;
  /** * Android 4.0 will call this method to get the database. * * @see android.content.contextwrapper#openorcreatedatabase (java.lang.String, int, * android.database.sqlite.SQLi
  Tedatabase.cursorfactory, * android.database.DatabaseErrorHandler) * @param name * @param mode * @param factory * @param ErrorHandler */@Override public sqlitedatabase openorcreatedatabase (String name, int mode, cursorfactory f Actory, Databaseerrorhandler ErrorHandler) {sqlitedatabase result = Sqlitedatabase.openorcreatedatabase (
  Getdatabasepath (name), NULL); return reSult; }
}

In the constructor of a subclass that inherits Sqliteopenhelper, the context can be replaced with an instance of Databasecontext:

Databasecontext DbContext = new Databasecontext (context);
Super (DbContext, mdatabasename, NULL, VERSION);

Based on how to implement the Android database to the SD card to save all the content to introduce so much, but also thank you all the time on the cloud Habitat Community website support, thank you.

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.