3

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
1
  • Did you try to change the path? You can get the path to your SD card programmatically with getExternalFilesDir() or getExternalStoragePublicDirectory() (have a look at developer.android.com/guide/topics/data/… for more details) Commented Feb 8, 2015 at 11:49

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the reply. Any idea what the cause of the problem is though?
@John: Sorry, my post was not completed: I guess the problem is either your path ("/...) or the fact that Android 4.3/4.4 doesn't allow to access every kind of contents on SD cards. You'll find a lot of information about this in the web.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.