AndroidStudio|读取SD卡中的sqlite数据

  • 从AndroidStudio assets目录复制文件到sd卡目录:(后两个参数表示sd卡路径及文件名称)
   public static boolean copyFileFromAssets(Context context, String filepath, String fileName) 
   {
        boolean result = false;
        try {
            if (!(new File(filepath +"/"+ fileName)).exists()) { //sd卡文件不存在
                File f = new File(filepath);
                if (!f.exists()) {
                    f.mkdir();
                }
                try {
                    InputStream is = context.getAssets().open(fileName); //assets资源文件
                    OutputStream os = new FileOutputStream(filepath +"/"+ fileName);
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = is.read(buffer)) > 0) {
                        os.write(buffer, 0, length);
                    }
                    os.flush();
                    os.close();
                    is.close();
                    result = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                result = true;
            }
        } catch (Exception e) {
            Log.d("fcj",e.toString());
        }
        return result;
    }

  • 处理sd卡SQL文件,需要通过继承SQLiteOpenHelper类,重写其构造方法。因为Android通过SQLiteOpenHelper创建数据库时,默认是将文件保存在'/data/data/应用程序名/databases'目录下,默认的SQLiteOpenHelper的构造方法调用了Context的openOrCreateDatabase方法,所以我们也需要继承Context类,重写openOrCreateDatabase方法,指定sd卡数据库路径。

  • 继承SQLiteOpenHelper :

public class SQLiteHelper extends SQLiteOpenHelper 
{
    public static String DATABASE_PATH = android.os.Environment
            .getExternalStorageDirectory().getAbsolutePath()+"/1SQL";

    public static String DB_NAME = "Identity.sqlite";

    public SQLiteHelper(Context context) {
        super(new SQLiteContext(context, getDirPath ()), DB_NAME, null, 1);
    }
    private static String getDirPath(){
        if(checkDataBase()) {
            return DATABASE_PATH;
        }
        return null;
    }
    public static boolean checkDataBase() { //查询该数据库文件是否存在
        SQLiteDatabase checkDB = null;
        try {
            String myPath = DATABASE_PATH +"/"+ DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
        } catch (SQLiteException e) {
            
        }
        if (checkDB != null) {
            checkDB.close();
        }
        return checkDB != null ? true : false;
    }
    @Override
    public void onOpen(SQLiteDatabase db) {
        super.onOpen(db);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}


  • 继承ContextWrapper:

public class SQLiteContext extends ContextWrapper 
{
    private String mDirPath; //sd卡文件路径,不包括文件名称
    public SQLiteContext(Context base,String dirPath){
        super(base);
         this.mDirPath=dirPath;
    }

    @Override
    public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler) {
        return super.openOrCreateDatabase( getDatabasePath (name).getAbsolutePath(), mode, factory, errorHandler);
    }

    @Override
    public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory) {
        return super.openOrCreateDatabase( getDatabasePath (name).getAbsolutePath(),mode, factory);
    }

    @Override
    public File getDatabasePath (String name) { //name:文件名称
        File result = new File( mDirPath +File.separator +name);
        if (!result.getParentFile().exists()){
            result.getParentFile().mkdirs();
        }
        return result;
    }
}


  • 查询数据,将数据转成图片:

     SQLiteHelper helper = new SQLiteHelper(this);
     SQLiteDatabase db = helper.getReadableDatabase();
     String[] columns = {"id", "photo", "name", "gender", "place"}; //你要的数据
     String[] selectionArgs = {"VBN97XnLE"}; //选择的目标值
      //查询identify表中,id=VBN97XnLE的数据
     Cursor cursor = db.query("identity", columns, "id=?", selectionArgs, null, null, null);
     while (cursor.moveToNext()) {
          int nameColumnIndex = cursor.getColumnIndex("photo"); //数据“photo”所在的列数
          byte[] strValue = cursor.getBlob(nameColumnIndex);
          Bitmap bitmap = BitmapFactory.decodeByteArray(strValue, 0, strValue.length);
          bitmapView.setImageBitmap(bitmap);
      }


  • 数据库数据

        AndroidStudio|读取SD卡中的sqlite数据




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Android Studio 数据存储通常分为以下几个部分:文件存储、SQLite数据库、ContentProviders以及各种内置的数据持久化API。这些工具帮助开发者在Android应用管理数据。 1. **文件存储(File Storage)**: - 使用`File`或`java.io`包可以直接操作设备的内部存储(Internal Storage)和外部存储(External Storage, 如SD卡)。 - `getExternalFilesDir()` 和 `getCacheDir()` 方法获取专用的文件路径用于存储应用缓存和数据。 2. **SQLite数据库**: - SQLite是一个轻量级的关系型数据库,使用它可以将数据持久化到应用内部,通过`SQLiteOpenHelper`和`Cursor` API进行CRUD(创建、读取、更新、删除)操作。 3. **ContentProviders**: - 为应用间共享数据提供机制,通过ContentResolver API可以查询、修改、删除其他应用的数据。 4. **SharedPreferences**: - 一种简单的键值对存储,适合存储少量、不常改动的数据,如应用设置。 5. **Room Persistence Library**(安卓X架构组件): - 一个ORM(对象关系映射)框架,提供了SQLite数据库的高级抽象,简化了数据存储和事务处理。 6. **Firebase Realtime Database/Cloud Firestore**: - Google提供的云数据库服务,支持实时同步和离线访问。 7. **Kotlin Coroutines/ViewModel**: - 在数据流库(LiveData、Flow)的帮助下,简化了数据获取和更新操作的异步管理。 相关问题: 1. Android Studio如何选择合适的存储方式? 2. 如何在Android Studio使用SQLite数据库创建和管理表? 3. ContentProviders的主要应用场景是什么? 4. SharedPreferences和SQLite数据持久化的优缺点分别是什么?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

烫青菜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值