Search code examples
androidsqlitestorage

Create database in External Storage


I know already how create Sqlite database. The point is the database file is created only in Internal Storage (/data/{package name})

Is there a way to directly create Sqlite database right on External Storage?


Solution

  • You can create your database like so:

    private SQLiteDatabase db;
    private yourPath = "/mnt/sdcard/";
    
    private SQLiteDatabase db = openOrCreateDatabase(yourPath + "sudoku.db", Context.MODE_PRIVATE, null);
    

    Edit Your methods:

    private static Cursor query(String query) {
        if (query != null) {
            openDB();
    
            while (db.isDbLockedByCurrentThread()) {
                // db in use, keep looping
            }
    
            Log.d("Query", query);
    
            return db.rawQuery(query, null);
        } else {
            return null;
        }
    }
    
    private static void openDB() {
        if (db == null) {
            db = SQLiteDatabase.openDatabase(yourPath + "sudoku.db", null, SQLiteDatabase.OPEN_READWRITE);
        }
    }