Reputation: 8058
Here is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SQLiteDatabase.openOrCreateDatabase("/gregpeck.db", null);
}
Obviously this is inside my Main Activity.
I have also added the permission to my Main Activity:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ie.callanan.dennis.testhw" >
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
The error message I receive is:
Failed to open database 'gregpeck.db'.
android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
Upvotes: 3
Views: 7000
Reputation: 13957
I would recommend to use a SQLiteOpenHelper
, if you need a private database for your application:
public class MyDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "DatabaseName";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_CREATE = "CREATE TABLE ....";
public MyDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(TABLE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase database,int oldVersion,int newVersion){
// do whatever is required for the upgrade
}
}
Here you find a full example. If you want to open a database from SD card, use:
File file = new File("/sdcard/db.sqlite" );
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(file, null);
Log.d("MyApp", "Successfully opened: " + db.isOpen());
For the first case you don't need any particular permissions. For the second one you do. Note: Android 4.3 and 4.4 do restrict the access on the SD card. So it might be that you cannot access the database file at all (see for instance this article).
Upvotes: 1