从sdcard打开SQLite数据库 - 没有这样的文件或目录

时间:2013-01-05 15:19:35

标签: android android-sqlite

答案就在这个帖子中: Sqlite issues with HTC Desire HD,感谢@Vikalp Patel

我正在做简单的事情 - 从sdcard打开sqlite数据库并从中读取一些东西。例如表格列表:

这是我的DataBaseHelper类(非常简单):

public class DataBaseHelper extends SQLiteOpenHelper{
    static Context mContext;
    private static SQLiteDatabase mDb;  

    public DataBaseHelper(Context context, String name, CursorFactory factory, int version) {
        super(context, name, factory, version);
        mContext = context;
    }           

//skip the overriden methods

    public void OpenDataBase(String path, String name){                     
        mDb = SQLiteDatabase.openDatabase(path + name, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);    

    }

    public Cursor GetTables(){      
        return mDb.rawQuery("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name", null);
    }

}

当我调用此代码时

mDbPath = Environment.getExternalStorageDirectory() + "/test_db/";
            mDbName = "db.sqlite";
            mDbHelper = new DataBaseHelper(mContext,mDbPath+mDbName,null,1);
            mDbHelper.OpenDataBase(mDbPath, mDbName);
            Toast.makeText(mContext, String.format("Database %s%s successfully opened", new Object[]{mDbPath, mDbName}), Toast.LENGTH_LONG).show();
            Cursor cursor = mDbHelper.GetTables();

返回的游标包含表列表。有用。唯一让我抓狂的是日志中的错误信息:

01-05 17:09:44.250: D/Database(21131): dbopen(): path = /mnt/sdcard/test_db/db.sqlite, flag = 2, file size = 3072
01-05 17:09:44.260: D/Database(21131): dbopen(): path = /mnt/sdcard/test_db/db.sqlite, mode: delete, disk free size: 3106 M, handle: 0x359260
01-05 17:09:44.260: I/Database(21131): sqlite returned: error code = 8, msg = statement aborts at 1: [pragma journal_mode = WAL;] 
01-05 17:09:44.260: W/Database(21131): dbopen(): sqlite3_exec to set journal_mode to WAL for /mnt/sdcard/test_db/db.sqlite failed
01-05 17:09:44.260: E/Database(21131): dbopen(): errno = 2, error message = No such file or directory

OpenDataBase方法中发生错误。

有人可以帮助我理解为什么会出现这个错误以及我做错了什么。 感谢。

编辑:我正在测试Android 2.3,HTC Desire HD

1 个答案:

答案 0 :(得分:0)

首先,不要在Android中使用硬编码路径 - 它们不能保证在所有设备上都相同。

尝试使用getDatabasePath("db_sqlite.db").getAbsolutePath();