携带SQLite数据库打包APK

思路:

       将写好的 xxx.db 文件放入 assetsraw 文件夹,这两个文件夹在打包时不会被压缩

在第一次打开程序时将 xxx.db文件复制到 /data/data/包名/database/xxx.db

包名用context.getPackageName()获取

InputStream的两种获取方式为:

  1. InputStream inputStream=context.getAssets().open(dbName);

      //数据库文件存于assets下

  2.InputStream is=context.getResources().openRawResource(R.raw.dbName);

     //数据库文件存于raw下

public class MoveSQLiteUtil {
    public static void move(Context context){
        String path="/data/data/"+ context.getPackageName()+"/databases/";
        String dbName="xxx.db";
        if(new File(context.getAssets().toString(),dbName).exists()){
            Log.d("OK","源文件不存在");
            return;
        }
        File file=new File(path+dbName);
        if(!file.exists()){
            //不存在
            File dir=new File(path);
            if(!dir.exists()){
                //文件夹不存在
                dir.mkdir();
                Log.d("OK","创建文件夹");
            }

            try {
                InputStream inputStream=context.getAssets().open(dbName);
                //InputStream inputStream =context.getResources().openRawResource(R.raw.dbName);
                OutputStream outputStream=new FileOutputStream(file);
                if(file.exists()){
                    Log.d("OK","收件文件创建成功");
                }
                else {
                    Log.d("OK","收件文件创建失败");
                }
                byte[] buffer = new byte[1024];
                int length;
                while ((length = inputStream.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, length);
                }
                // 关闭文件流
                outputStream.flush();
                outputStream.close();
                inputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            Log.d("OK","数据库复制成功");
        }
        else {
            //存在
            Log.d("OK","数据库存在");
        }
    }
}

注意:

1.创建MySQLiteOpenHelper要将数据库名换为 xxx.db

public MySQLiteOpenHelper(Context context) {
    super(context,"xxx.db",null,2);
}

2.查询后得到Cursor,读取前要先移动指针

cursor.moveToNext();   第一次读取结果也要移动指针

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

在下嗷呜

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

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

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

打赏作者

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

抵扣说明:

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

余额充值