Android P - 从资产复制数据库后“SQLite:没有此类表错误" [英] Android P - 'SQLite: No Such Table Error' after copying database from assets

查看:24
本文介绍了Android P - 从资产复制数据库后“SQLite:没有此类表错误"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据库保存在我的应用程序资产文件夹中,我在应用程序首次打开时使用以下代码复制数据库.

I have a database saved in my apps assets folder and I copy the database using the below code when the app first opens.

inputStream = mContext.getAssets().open(Utils.getDatabaseName());

        if(inputStream != null) {

            int mFileLength = inputStream.available();

            String filePath = mContext.getDatabasePath(Utils.getDatabaseName()).getAbsolutePath();

            // Save the downloaded file
            output = new FileOutputStream(filePath);

            byte data[] = new byte[1024];
            long total = 0;
            int count;
            while ((count = inputStream.read(data)) != -1) {
                total += count;
                if(mFileLength != -1) {
                    // Publish the progress
                    publishProgress((int) (total * 100 / mFileLength));
                }
                output.write(data, 0, count);
            }
            return true;
        }

上面的代码运行没有问题,但是当您尝试查询数据库时,您会得到一个 SQLite:没有这样的表异常.

The above code runs without problem but when you try to query the database you get an SQLite: No such table exception.

此问题仅在 Android P 中出现,所有早期版本的 Android 都可以正常工作.

This issue only occurs in Android P, all earlier versions of Android work correctly.

这是 Android P 的已知问题还是有什么变化?

Is this a known issue with Android P or has something changed?

推荐答案

这个问题在 Android P 上导致崩溃的频率似乎比在以前的版本上要高得多,但这并不是 Android P 本身的错误.

This issue seems to lead to a crash much more often on Android P than on previous versions, but it's not a bug on Android P itself.

问题在于,您将值分配给 String filePath 的行打开了与数据库的连接,当您从资产复制文件时,该连接保持打开状态.

The problem is that your line where you assign the value to your String filePath opens a connection to the database that remains open when you copy the file from assets.

要解决问题,请更换线

String filePath = mContext.getDatabasePath(Utils.getDatabaseName()).getAbsolutePath();

用代码获取文件路径值然后关闭数据库:

with code to get the file path value and then close the database:

MySQLiteOpenHelper helper = new MySQLiteOpenHelper();
SQLiteDatabase database = helper.getReadableDatabase();
String filePath = database.getPath();
database.close();

并且还添加了一个内部助手类:

And also add an inner helper class:

class MySQLiteOpenHelper extends SQLiteOpenHelper {

    MySQLiteOpenHelper(Context context, String databaseName) {
        super(context, databaseName, null, 2);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
    }

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

这篇关于Android P - 从资产复制数据库后“SQLite:没有此类表错误"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆