Why are sqlite databases located on sdcard readonl

2019-05-30 09:39发布

问题:

I have posted this question over a week ago on the Android dev list but so far no responses.

I have run into a weird issue. I work with a database located on /sdcard/ and for some reason whenever I add <uses-sdk android:minSdkVersion="8" /> to the manifest sqlite opens the db as read only. It gets a bit weirder too. The below code opens the db and checks if the db is readonly, which returns false:

db = SQLiteDatabase.openDatabase("/sdcard/test.db3", null, SQLiteDatabase.OPEN_READWRITE); Log.i(LOGTAG, "Database status: " + db.isReadOnly());

but if I try to write any data it bombs with:

INFO/Database(6576): sqlite returned: error code = 8, msg = prepared statement aborts at 24: [INSERT INTO tags(type_id , tag) VALUES(?, ?);] ERROR/Database(6576): Error inserting type_id =1 tag=TestTag ERROR/Database(6576): android.database.sqlite.SQLiteException: error code 8: attempt to write a readonly database

If I remove the uses-sdk tag from manifest everything works fine. I verified this behavior on the emulator, NexusOne running 2.2.1 and Galaxy Tab. Is this a known issue? Is there a workaround?

Any help will be greatly appreciated.

回答1:

You need the WRITE_EXTERNAL_STORAGE permission.

Also, never never never never never hardcode the path to external storage the way you are doing. Your code will break on Android 2.2 devices. Your code will break on other devices. Use Environment.getExternalStorageDirectory(), please.