Failed to open Database Android Java SQLite

前端 未结 1 375
一个人的身影
一个人的身影 2021-01-14 16:25

Here is my code:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

           


        
相关标签:
1条回答
  • 2021-01-14 16:55

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

    0 讨论(0)
提交回复
热议问题