Wednesday, March 14, 2012

How to create your Database in an accessible folder in Android

When you run your codes in Android, you really cant access the DB files created automatically inside Android. So here is how to save it on your SDcard.

Override the following method in your activity class.
@Override
 public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory){
  File externalFilesDir = Environment.getExternalStorageDirectory();
   if(externalFilesDir == null) 
          return null;
   File dbFile = new File(externalFilesDir, DBConstant.DATABASE_NAME);
   return SQLiteDatabase.openDatabase(dbFile.getAbsolutePath(), null, SQLiteDatabase.CREATE_IF_NECESSARY);

Now you are good to go. I used SQLiteOpenHelper to manage my insertion of data. What i did can found below. You change it for your use.

public class MyDataHelper extends SQLiteOpenHelper{
 
 private static final String DATABASE_NAME = "events.db" ;
 private static final int DATABASE_VERSION = 1;
 
 /** Create a helper object for the Events database */
 public DBgpsDataHelper(Context ctx) {
  super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
 }
 
 @Override
 public void onCreate(SQLiteDatabase db) {
  db.execSQL("CREATE TABLE " + TABLE_NAME + " (" + 
    _ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + 
    TIME + " INTEGER, " + ");
 }

 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  // TODO Auto-generated method stub
  
 }
}

Enjoy!