How Can I Read The Db In My Android App Which I've Modified In My Pc And Copied Back To My App's Db Folder
Solution 1:
First I will explain how to copy existing database schema in Android app and good practices to deal with SQLite DB
, so that it will be helpful to others as well. This way is useful when you have static database schema.
Recommended way to use database object in Android application is, create it at application level and use it through out the application.
publicclassMyApplicationextendsApplication{
public DBHelper dbHelper;
@OverridepublicvoidonCreate() {
super.onCreate();
dbHelper = newDBHelper(getApplicationContext());
try {
dbHelper.createDataBase();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Don't forgot to mention your application name in AndroidManifest file in application
tag.Suppose your application class name is MyApplication and it resides in com.app package then it should be :-
android:name="com.app.MyApplication"
Below is DBHelper class which working as a bridge between our application and local database.
publicclassDBHelperextendsSQLiteOpenHelper{
publicstaticfinalStringDATABASE_NAME="Your database name";
publicstaticfinalintDATABASE_VERSION=1;
privatestaticStringDB_PATH="";
private SQLiteDatabase mDataBase;
privatefinal Context mContext;
/**
* Called when the database is created for the first time. This is where the
* creation of tables and the initial population of the tables should happen.
*
* @param db The database.
*/@OverridepublicvoidonCreate(SQLiteDatabase db) {
}
/**
* Called when the database needs to be upgraded. The implementation
* should use this method to drop tables, add tables, or do anything else it
* needs to upgrade to the new schema version.
* <p/>
* <p>
* The SQLite ALTER TABLE documentation can be found
* <a href="http://sqlite.org/lang_altertable.html">here</a>. If you add new columns
* you can use ALTER TABLE to insert them into a live table. If you rename or remove columns
* you can use ALTER TABLE to rename the old table, then create the new table and then
* populate the new table with the contents of the old table.
* </p><p>
* This method executes within a transaction. If an exception is thrown, all changes
* will automatically be rolled back.
* </p>
*
* @param db The database.
* @param oldVersion The old database version.
* @param newVersion The new database version.
*/@OverridepublicvoidonUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
/**
* Create a helper object to create, open, and/or manage a database.
* This method always returns very quickly. The database is not actually
* created or opened until one of {@link #getWritableDatabase} or
* {@link #getReadableDatabase} is called.
*
* @param context to use to open or create the database
*/publicDBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
if(android.os.Build.VERSION.SDK_INT >= 17){
DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
}
else
{
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
}
this.mContext = context;
}
/**
Check if the database already exist to avoid re-copying the file each time you open the application.
* @return true if it exists, false if it doesn't
*/publicbooleancheckDataBase(){
SQLiteDatabasecheckDB=null;
try{
StringmyPath= DB_PATH + DATABASE_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
//database does't exist yet.
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Creates a empty database on the system and rewrites it with your own database.
* */publicvoidcreateDataBase()throws IOException {
booleandbExist= checkDataBase();
if(dbExist){
//do nothing - database already exist
}else{
//By calling this method and empty database will be created into the default system path//of your application so we are gonna be able to overwrite that database with our database.this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
thrownewError("Error copying database");
}
}
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */privatevoidcopyDataBase()throws IOException{
//Open your local db as the input streamInputStreammyInput= mContext.getAssets().open(DATABASE_NAME+".sqlite");
// Path to the just created empty dbStringoutFileName= DB_PATH + DATABASE_NAME;
//Open the empty db as the output streamOutputStreammyOutput=newFileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfilebyte[] buffer = newbyte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
publicvoidopenDataBase()throws SQLException {
//Open the databaseStringmyPath= DB_PATH + DATABASE_NAME;
mDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
@Overridepublicsynchronizedvoidclose() {
if(mDataBase != null)
mDataBase.close();
super.close();
}
}
Now this might be solution for your problem. You just need to open the database from your activity, do database operations and after done with it just close it. Below is code snippet :-
MyApplicationapplication= (MyApplication) getApplicationContext();
application.dbHelper.openDataBase();
boolean isInserted=application.dbHelper.insertData(editname.getText().toString(),editsurname.getText().toString(),editmarks.getText().toString());
application.dbHelper.close();
I hope this will help you.
Post a Comment for "How Can I Read The Db In My Android App Which I've Modified In My Pc And Copied Back To My App's Db Folder"