Read External Database with SQLiteOpenHelper on Android
May 26, 2018
To access external SQLite database that store in external storage. In Android SQLiteOpenHelper class by default can access only default data path “data/data/package_name/” this directory.
So, here is a example of how you can access external database from your android application.
Keep in mind that your application has permission to read and write in External SD card in Android manifest.
Step 1:
First, you need to create a contextWrapper that will help you to change the default path in SQLiteOpenHelper class.
Example of contextWrapper:
public class DatabaseContext extends ContextWrapper { private static final String DEBUG_CONTEXT = «DatabaseContext»; public DatabaseContext(Context base) { super(base); } @Override public File getDatabasePath(String name) { File sdcard = Environment.getExternalStorageDirectory(); String dbfile = sdcard.getAbsolutePath() + File.separator+ «database» + File.separator + name; if (!dbfile.endsWith(«.db»)) { dbfile += «.db» ; } File result = new File(dbfile); if (!result.getParentFile().exists()) { result.getParentFile().mkdirs(); } if (Log.isLoggable(DEBUG_CONTEXT, Log.WARN)) { Log.w(DEBUG_CONTEXT, «getDatabasePath(» + name + «) = » + result.getAbsolutePath()); } return result; } /* this version is called for android devices >= api-11. thank to @damccull for fixing this. */ @Override public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler) { return openOrCreateDatabase(name,mode, factory); } /* this version is called for android devices < api-11 */ @Override public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory) { SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), null); if (Log.isLoggable(DEBUG_CONTEXT, Log.WARN)) { Log.w(DEBUG_CONTEXT, "openOrCreateDatabase(" + name + ",,) = " + result.getPath()); } return result; } }}
this wrapper class will take care of all necessary steps to external database path.
Step 2:
public class DatabaseHelper extends SQLiteOpenHelper { public DatabaseHelper(Context context, String name) { super(new DatabaseContext(context), name, null, 1); } @Override public void onCreate(SQLiteDatabase db) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }}
Now create a class DataBaseHelper that extend SQLiteOpenHelper class :
Step 3:
public class MyDatabase { private DatabaseHelper databaseHelper; private SQLiteDatabase database; private ArrayListFinally create a class that we can instantiate DataBaseHelper class to read and write to our database
Example:
}
In this way you can read and write to external database.
Thank you for reading. 🙂 🙂