iis服务器助手广告广告
返回顶部
首页 > 资讯 > 移动开发 >基于Android如何实现将数据库保存到SD卡
  • 626
分享到

基于Android如何实现将数据库保存到SD卡

sdsd卡数据库数据Android 2022-06-06 09:06:48 626人浏览 八月长安
摘要

有时候为了需要,会将数据库保存到外部存储或者SD卡中(对于这种情况可以通过加密数据来避免数据被破解),比如一个应用支持多个数据,每个数据都需要有一个对应的数据库,并且数据库中的

有时候为了需要,会将数据库保存到外部存储或者SD卡中(对于这种情况可以通过加密数据来避免数据被破解),比如一个应用支持多个数据,每个数据都需要有一个对应的数据库,并且数据库中的信息量特别大时,这显然更应该将数据库保存在外部存储或者SD卡中,因为RAM的大小是有限的;其次在写某些测试程序时将数据库保存在SD卡更方便查看数据库中的内容。

Android通过sqliteOpenHelper创建数据库时默认是将数据库保存在'/data/data/应用程序名/databases'目录下的,只需要在继承SQLiteOpenHelper类的构造函数中传入数据库名称就可以了,但如果将数据库保存到指定的路径下面,都需要通过重写继承SQLiteOpenHelper类的构造函数中的context,因为:在阅读SQLiteOpenHelper.java的源码时会发现:创建数据库都是通过Context的openOrCreateDatabase方法实现的,如果我们需要在指定的路径下创建数据库,就需要写一个类继承Context,并复写其openOrCreateDatabase方法,在openOrCreateDatabase方法中指定数据库存储的路径即可,下面为类SQLiteOpenHelper中getWritableDatabase和getReadableDatabase方法的源码,SQLiteOpenHelper就是通过这两个方法来创建数据库的。



 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 (mIsInitializing) {
   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 lock to be held on
  // the file, and our attempts to open the database read-write would
  // fail waiting for the file lock. 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();
   }
  }
 }
 
 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 (will 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();
  }
 }

通过上面的分析可以写出一个自定义的Context类,该类继承Context即可,但由于Context中有除了openOrCreateDatabase方法以外的其它抽象函数,所以建议使用非抽象类ContextWrapper,该类继承自Context,自定义的DatabaseContext类源码如下:


public class DatabaseContext extends ContextWrapper {
 public DatabaseContext(Context context){
  super( context );
 }
 
 @Override
 public File getDatabasePath(String name) {
  //判断是否存在sd卡
  boolean sdExist = android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment.getExternalStorageState());
  if(!sdExist){//如果不存在,
   return null;
  }else{//如果存在
   //获取sd卡路径
   String dbDir= FileUtils.getFlashBPath();
   dbDir += "DB";//数据库所在目录
   String dbPath = dbDir+"/"+name;//数据库路径
   //判断目录是否存在,不存在则创建该目录
   File dirFile = new File(dbDir);
   if(!dirFile.exists()){
    dirFile.mkdirs();
   }
   //数据库文件是否创建成功
   boolean isFileCreateSuccess = false; 
   //判断文件是否存在,不存在则创建该文件
   File dbFile = new File(dbPath);
   if(!dbFile.exists()){
    try {   
     isFileCreateSuccess = dbFile.createNewFile();//创建文件
    } catch (IOException e) {
     e.printStackTrace();
    }
   }else{
    isFileCreateSuccess = true;
   }
   //返回数据库文件对象
   if(isFileCreateSuccess){
    return dbFile;
   }else{
    return null;
   }
  }
 }
 
 @Override
 public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory) {
  SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), null);
  return result;
 }
 
 @Override
 public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory, DatabaseErrorHandler errorHandler) {
  SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), null);
  return result;
 }
}

在继承SQLiteOpenHelper的子类的构造函数中,用DatabaseContext的实例替代context即可:


DatabaseContext dbContext = new DatabaseContext(context);
super(dbContext, mDatabaseName, null, VERSION);

基于Android如何实现将数据库保存到SD卡的全部内容就给大家介绍这么多,同时也非常感谢大家一直以来对编程网网站的支持,谢谢。

您可能感兴趣的文章:android 拷贝sqlite数据库到本地sd卡的方法Android sd卡读取数据库实例代码Android 数据库SQLite 写入SD卡的方法android编程实现sd卡读取数据库的方法Android数据库SD卡创建和图片存取操作


--结束END--

本文标题: 基于Android如何实现将数据库保存到SD卡

本文链接: https://www.lsjlt.com/news/26177.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作