简体   繁体   English

SQLiteAssetHelper:无法打开数据库进行写入(将尝试只读)

[英]SQLiteAssetHelper:Couldn't open database for writing (will try read-only)

This question has already been asked by the people but going through the steps from many of them I am still unable to fix the problem at my end, My app is working fine on emulator but not on the real device and gives the following 2 exceptions, the first exception is the major source of second exception and i guess there is some permission issue. 这个问题已经被人们问了,但是经历了很多人的步骤我仍然无法解决问题,我的应用程序在模拟器上工作正常,但在真实设备上没有,并给出以下2个例外情况,第一个例外是第二个例外的主要来源,我猜有一些许可问题。 I have added the 我添加了

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

to the manifest file but i got the same result. 到清单文件,但我得到了相同的结果。 My database is very simple with one table. 我的数据库非常简单,只有一个表。 ALso i have added "android_metadata" table and edit my other table's id field to "_id". 另外我添加了“android_metadata”表并将我的其他表的id字段编辑为“_id”。 and I am sure my database is present in the assets folder. 我确信我的数据库存在于assets文件夹中。

Any help would be appreciated. 任何帮助,将不胜感激。

first exception 第一个例外

02-24 12:58:10.067: E/SQLiteAssetHelper(7107): Couldn't open Shajra for writing (will try read-only):
02-24 12:58:10.067: E/SQLiteAssetHelper(7107): com.readystatesoftware.sqliteasset.SQLiteAssetHelper$SQLiteAssetException: Missing databases/Shajra file (or .zip, .gz archive) in assets, or target folder not writable
02-24 12:58:10.067: E/SQLiteAssetHelper(7107):  at android.content.res.AssetManager.openAsset(Native Method)
02-24 12:58:10.067: E/SQLiteAssetHelper(7107):  at android.content.res.AssetManager.open(AssetManager.java:325)
02-24 12:58:10.067: E/SQLiteAssetHelper(7107):  at android.content.res.AssetManager.open(AssetManager.java:299)
02-24 12:58:10.067: E/SQLiteAssetHelper(7107):  at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.copyDatabaseFromAssets(SQLiteAssetHelper.java:436)
02-24 12:58:10.067: E/SQLiteAssetHelper(7107):  at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.createOrOpenDatabase(SQLiteAssetHelper.java:400)
02-24 12:58:10.067: E/SQLiteAssetHelper(7107):  at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.getWritableDatabase(SQLiteAssetHelper.java:176)
02-24 12:58:10.067: E/SQLiteAssetHelper(7107):  at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.getReadableDatabase(SQLiteAssetHelper.java:254)
02-24 12:58:10.067: E/SQLiteAssetHelper(7107):  at com.nannandotcom.MainActivity.onCreate(MainActivity.java:27)
02-24 12:58:10.067: E/SQLiteAssetHelper(7107):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1072)
02-24 12:58:10.067: E/SQLiteAssetHelper(7107):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1836)
02-24 12:58:10.067: E/SQLiteAssetHelper(7107):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1893)
02-24 12:58:10.067: E/SQLiteAssetHelper(7107):  at android.app.ActivityThread.access$1500(ActivityThread.java:135)
02-24 12:58:10.067: E/SQLiteAssetHelper(7107):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1054)
02-24 12:58:10.067: E/SQLiteAssetHelper(7107):  at android.os.Handler.dispatchMessage(Handler.java:99)
02-24 12:58:10.067: E/SQLiteAssetHelper(7107):  at android.os.Looper.loop(Looper.java:150)
02-24 12:58:10.067: E/SQLiteAssetHelper(7107):  at android.app.ActivityThread.main(ActivityThread.java:4389)
02-24 12:58:10.067: E/SQLiteAssetHelper(7107):  at java.lang.reflect.Method.invokeNative(Native Method)
02-24 12:58:10.067: E/SQLiteAssetHelper(7107):  at java.lang.reflect.Method.invoke(Method.java:507)
02-24 12:58:10.067: E/SQLiteAssetHelper(7107):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:849)
02-24 12:58:10.067: E/SQLiteAssetHelper(7107):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:607)
02-24 12:58:10.067: E/SQLiteAssetHelper(7107):  at dalvik.system.NativeStart.main(Native Method)

second exception 第二个例外

02-24 12:58:10.077: E/Database(7107): dbopen(): sqlite3_open_v2("/data/data/com.example.nannandotcom/databases/Shajra", &handle, 1, NULL) failed
02-24 12:58:10.077: E/Database(7107): dbopen(): errno = 2, error message = No such file or directory
02-24 12:58:10.077: D/AndroidRuntime(7107): Shutting down VM
02-24 12:58:10.077: W/dalvikvm(7107): threadid=1: thread exiting with uncaught exception (group=0x4011f5a0)
02-24 12:58:10.108: E/AndroidRuntime(7107): FATAL EXCEPTION: main
02-24 12:58:10.108: E/AndroidRuntime(7107): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.nannandotcom/com.nannandotcom.MainActivity}: android.database.sqlite.SQLiteException: unable to open database file
02-24 12:58:10.108: E/AndroidRuntime(7107):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1872)
02-24 12:58:10.108: E/AndroidRuntime(7107):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1893)
02-24 12:58:10.108: E/AndroidRuntime(7107):     at android.app.ActivityThread.access$1500(ActivityThread.java:135)
02-24 12:58:10.108: E/AndroidRuntime(7107):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1054)
02-24 12:58:10.108: E/AndroidRuntime(7107):     at android.os.Handler.dispatchMessage(Handler.java:99)
02-24 12:58:10.108: E/AndroidRuntime(7107):     at android.os.Looper.loop(Looper.java:150)
02-24 12:58:10.108: E/AndroidRuntime(7107):     at android.app.ActivityThread.main(ActivityThread.java:4389)
02-24 12:58:10.108: E/AndroidRuntime(7107):     at java.lang.reflect.Method.invokeNative(Native Method)
02-24 12:58:10.108: E/AndroidRuntime(7107):     at java.lang.reflect.Method.invoke(Method.java:507)
02-24 12:58:10.108: E/AndroidRuntime(7107):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:849)
02-24 12:58:10.108: E/AndroidRuntime(7107):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:607)
02-24 12:58:10.108: E/AndroidRuntime(7107):     at dalvik.system.NativeStart.main(Native Method)
02-24 12:58:10.108: E/AndroidRuntime(7107): Caused by: android.database.sqlite.SQLiteException: unable to open database file
02-24 12:58:10.108: E/AndroidRuntime(7107):     at android.database.sqlite.SQLiteDatabase.dbopen(Native Method)
02-24 12:58:10.108: E/AndroidRuntime(7107):     at android.database.sqlite.SQLiteDatabase.<init>(SQLiteDatabase.java:1962)
02-24 12:58:10.108: E/AndroidRuntime(7107):     at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:906)
02-24 12:58:10.108: E/AndroidRuntime(7107):     at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.getReadableDatabase(SQLiteAssetHelper.java:264)
02-24 12:58:10.108: E/AndroidRuntime(7107):     at com.nannandotcom.MainActivity.onCreate(MainActivity.java:27)
02-24 12:58:10.108: E/AndroidRuntime(7107):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1072)
02-24 12:58:10.108: E/AndroidRuntime(7107):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1836)
02-24 12:58:10.108: E/AndroidRuntime(7107):     ... 11 more

DatabaseHelper DatabaseHelper

package com.nannandotcom;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.nannandotcom.model.ProfileBean;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;

public class DatabaseHelper extends SQLiteAssetHelper {

    private static final String DATABASE_NAME = "Shajra";
    private static final int DATABASE_VERSION = 1;

    private Context context;

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    }

    public void copyDatabase() throws IOException{
    //  SQLiteDatabase checkDB = SQLiteDatabase.openDatabase(context.getAssets().+(DATABASE_NAME), null, SQLiteDatabase.OPEN_READONLY);
    //  checkDB.close();
    InputStream myInput = context.getAssets().open(DATABASE_NAME);      
    String outFileName =  "/data/data/"+ context.getPackageName() + "/databases/" + DATABASE_NAME;     
    OutputStream myOutput = new FileOutputStream(outFileName);

    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))>0){
        myOutput.write(buffer, 0, length);
    }

    myOutput.flush();
    myOutput.close();
    myInput.close();
    }

    public ProfileBean getProfileBean(SQLiteDatabase database,int id){
        ProfileBean profileBean = new ProfileBean();
        try {
            Cursor c = database.query("Profiles",
                    new String[]{"_id","Name","Qualification","WorkingAt","LivesAt","MaritalStatus","NumberOfChildren",
                    "Telephone","Email","Picture","MarriedTo","Father","Mother","DOB","Gender"},
                    "_id=?",
                    new String[]{Integer.toString(id)},null, null, null);
            if (c != null ) {
                if  (c.moveToFirst()) {
                    do {

                    }while (c.moveToNext());
                } 
            }   
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return profileBean;
    }
}

MainActivity 主要活动

package com.nannandotcom;

import java.io.IOException;
import com.example.nannandotcom.R;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        DatabaseHelper databaseHelper = new DatabaseHelper(this);
        SQLiteDatabase database = databaseHelper.getReadableDatabase();

        try {
            databaseHelper.copyDatabase();
    }   
        }catch(SQLException sqle){

            throw sqle;

        }
        }
        catch(Exception e){
            Log.e("MainActivity", e.getMessage());
            e.printStackTrace();
        }

        final EditText enterName = (EditText) findViewById(R.id.editText1);
        Button submit = (Button) findViewById(R.id.button1);
        submit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent mainActivityIntent = new   Intent(MainActivity.this, Welcome.class);
                mainActivityIntent.putExtra("userName", enterName.getText().toString());
                startActivity(mainActivityIntent);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

i think you are missing db extension in DATABASE_NAME . 我认为您在DATABASE_NAME中缺少数据库扩展。

So give specific DATABASE_NAME with extension as per assets directory. 因此,请根据资产目录为特定DATABASE_NAME提供扩展名。

Replace 更换

private static final String DATABASE_NAME = "Shajra"; 

With

private static final String DATABASE_NAME = "Shajra.db"; 

Or 要么

private static final String DATABASE_NAME = "Shajra.sqlite"; 

The same problem bothering me for whole night, my solution: 同样的问题困扰着我整夜,我的解决方案:

Create "assets" folder in Android Studio by using the official way: Right Click your app module -> new -> folder -> assets 使用官方方式在Android Studio中创建“assets”文件夹: 右键单击您的应用程序模块 - >新建 - >文件夹 - >资产

Android Studio may also change DATABASE_NAME without you knowing it... Android Studio也可能在您不知情的情况下更改DATABASE_NAME ...

Put db file in assets/databases subdirectory. db文件放在assets/databases子目录中。

And then be sure to change 然后一定要改变

private static final String DATABASE_NAME = "databases/mydb.db";

to

private static final String DATABASE_NAME = "mydb.db";

This was my problem 这是我的问题

oh , that was my bad problem and finally i found the solution! 哦,这是我的坏问题,最后我找到了解决方案!

so you should rename your database file ,Start with a small letter and then 所以你应该重命名你的数据库文件,然后用一个小写字母开头

private static final String DATABASE_NAME = "mydata.db";
    private static final int DATABASE_VERSION = 1;

    public DatabaseOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

In my case SQLiteHelper extends SQLiteOpenHelper , then I´ve got a custom class that makes use of this SQLiteHelper with the next 3 methods (initialization, open and close). 在我的例子中, SQLiteHelper扩展了SQLiteOpenHelper ,然后我有一个自定义类,它使用这个SQLiteHelper和接下来的3个方法(初始化,打开和关闭)。 Take a look at the dbHelper.getWritableDatabase(); 看一下dbHelper.getWritableDatabase(); method please. 方法请。 That might be the one you need. 那可能就是你需要的那个。

private SQLiteDatabase database;
private SQLiteHelper dbHelper;

public CallHistoryDataSource(Context context) {
    dbHelper = new SQLiteHelper(context);
}

private void open() throws SQLException {
    database = dbHelper.getWritableDatabase();
}

private void close() {
    dbHelper.close();
}

When you are copying your db to SD Card use this way to assign the path. 将数据库复制到SD卡时,请使用此方法分配路径。

String outFileName =  Environment.getExternalStorageDirectory() + "/databases/" + DATABASE_NAME;     

Only if it's successful, if you want to just read records from database, you need to call databaseHelper.getReadableDatabase(); 只有它成功,如果你只想从数据库中读取记录,你需要调用databaseHelper.getReadableDatabase(); or if you want to read & write both you need to call databaseHelper.getWritableDatabase(); 或者如果你想读写两个,你需要调用databaseHelper.getWritableDatabase();

For me, it throws the same error and I resolved with the Following Steps 对我来说,它会抛出相同的错误,我解决了以下步骤

Step 1: Added the Permissions 第1步:添加权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Step 2: Added the Runtime Permissions 第2步:添加运行时权限

if (ContextCompat.checkSelfPermission(MainActivity.this,
                Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    101);
        }else {
            db=new DbUtils(MainActivity.this);
        }

Step 3: Changed the File Name in Assets folder as mentioned in Below 第3步:更改Assets文件夹中的文件名,如下所述

private static final String DATABASE_NAME = "thirukkural.db";

File Name inside Asset Folder(this cause the error ) 资产文件夹中的文件名(导致错误)

Old File Name thirukkural 旧文件名 thirukkural

NewFile Name thirukkural.db NewFile名称 thirukkural.db

Note: File Name with out Extension 注意: 文件名没有扩展名

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM