0

I want to pre-create database for my android app. I use "SQLite Database Browser" and after create my database, i have copy the database to app folder "databases". In my app side i have add permission to write in sdcard (if need it)

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

and my code to open the database is:

    String myPath = getApplicationContext().getFilesDir().getAbsolutePath().replace("files","databases")+ File.separator + "mydb.db";
    db = SQLiteDatabase.openOrCreateDatabase(myPath, null);

Android can't to open my database and showing this error:

    android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database

I have try the followings:

  • I have open the database file with Notepad++ and i confirmed the SQL format "SQLite format 3" in the header of the file.
  • I have add "android_metadata" table from "SQLite Database Browser" with this SQL statement:

    CREATE TABLE "android_metadata" ("locale" TEXT DEFAULT 'en_US');
    INSERT INTO "android_metadata" VALUES ('en_US')
    
  • I have try to delete my database file from android and run my app to check if code can create database with this name and all it's ok, dabase created with no problems, after that i have run again my app to check if it can open the database and opening with no problems. I have create all tables i need it with android code and after succesfully database created, i have copy this file back to windows and opening with "SQLite Database Browser" to insert few data into table and after save changes, copy again back to android, but my app it can't to open it again!

I'm confused, where is the problem? Why if i try to edit or create database with "SQLite Database Browser" android it can't to open this?

Sorry for my english...

*Version of "SQLite Database Browser" is 3.9.1

Azzabi Haythem
  • 2,318
  • 7
  • 26
  • 32
  • 1
    If you run your app is in API >=23 then you need to get dynamic permission. and you get that dynamic permission like this http://stackoverflow.com/questions/39404356/i-have-to-programmatically-retrieve-permissions-group-from-the-manifest-xml-of-a/39410610#39410610 – Farmer Oct 17 '16 at 15:31
  • Yes, you are correct! Thank You! Now it's working! But is very strange, why android app can it create database file and open it without problems and if you edit or create this file from "SQLite Database Browser" it can't? Very strange! Thank You again! – Vasileios Delimaras Oct 17 '16 at 17:01

1 Answers1

0

Please make sure that you file path is empty or not. First you check that then after open it

String myPath = getApplicationContext().getFilesDir().getAbsolutePath().replace("files","databases")+ File.separator + "mydb.db";
File file = new File(myPath);    
if (file.exists() && !file.isDirectory())
{
      db = SQLiteDatabase.openOrCreateDatabase(myPath, null);
}
else
{
      Log.i(TAG, "Database file not found");
}
Farmer
  • 4,093
  • 3
  • 23
  • 47