Android open or create database

送分小仙女□ 提交于 2019-12-09 13:21:11

问题


I am trying to create a database on my sd card. Whenever I call SQLiteDatabase.openOrCreateDatabase I get the error:

07-21 13:33:17.587: ERROR/AndroidRuntime(5541): Caused by: android.database.sqlite.SQLiteException: unable to open database file

Does anyone know what may be causing this? Here is the code I have in the open() method of my database class:

File sdcard = Environment.getExternalStorageDirectory();

String dbfile = sdcard.getAbsolutePath() + File.separator+ "external_sd" + File.separator + Schema.DATABASE_NAME ;

db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);

回答1:


One possible fault on this could be that you did not set the appropriate permissions

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

However storing data on a SD Card is considered to be insecure. Because every application which has permissions to store data on the sd storage could access the database.

Edit: Another possible problem is that external storage may not be available. You need to make sure that your external storage is currently writeable. One method would be to determine the state via getExternalStorageState (see reference here).

getExternalStorageState() returns MEDIA_SHARED if the media is present not mounted, and shared via USB mass storage. 

Reference. There is also a stackoverflow post on checking the state here: Writing Text File to SD Card fails




回答2:


public static final String DATABASE_PATH=Environment.getExternalStorageDirectory().getAbsolutePath()+"/WebService/Databases/";


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


SQLiteDatabase db=SQLiteDatabase.openDatabase(DATABASE_PATH+DATABASE_NAME,null,SQLiteDatabase.CREATE_IF_NECESSARY | SQLiteDatabase.OPEN_READWRITE);


来源:https://stackoverflow.com/questions/6780982/android-open-or-create-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!