How to replace my sqlite database with the new one while updating application?

177 views Asked by At

How can i update my sqlite database without need for uninstalling my android application. I build my db with the database manager named 'Sqlite Expert'... and copy the result to the assets folder of my project. Here is my Database.java to do database job:

public class Database extends SQLiteOpenHelper {

private static final String dbInstallationPath = "/data/data/com.example.asus.android/databases/";
private static final String dbName = "database";
private static final int dbVersion = 2;
private final Context mycontext;
public SQLiteDatabase mydb;


public Database(Context context) {
    super(context, dbName, null, dbVersion);
    mycontext = context;
}


@Override
public void onCreate(SQLiteDatabase arg0) {
    // TODO Auto-generated method stub

    Log.d("oncreate", "oncreated was called..s");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    db.execSQL("DROP TABLE IF EXISTS " + "content");
    onCreate(db);
    try {
        copydatabase();
    } catch (IOException e) {
        e.printStackTrace();
    }
    Log.d("databaseupdate", "db was updaatedd.");
}


public void usable() {
    if (checkdb()) {
    } else {
        this.getReadableDatabase();
        try {
            copydatabase();
            Log.d("copy successful", "conpy done! dsyccesful...");
        } catch (IOException e) {
            Log.d("copydatabase()", "IOExcptons fFor copyyingdatabasde");
        }
    }
    Log.d("usable", "usable called.");
}

public void open() {
    mydb = SQLiteDatabase.openDatabase(dbInstallationPath + dbName, null, SQLiteDatabase.OPEN_READWRITE);
}

public void close() {
    mydb.close();
}

public boolean checkdb() {

    SQLiteDatabase db = null;
    try {
        db = SQLiteDatabase.openDatabase(dbInstallationPath + dbName, null, SQLiteDatabase.OPEN_READONLY);
    } catch (SQLException e) {
        Log.d("new", "the database coudlnt be opened..fghf");

    }

    return db != null ? true : false;

}


public void copydatabase() throws IOException {
    OutputStream myOutput = new FileOutputStream(dbInstallationPath + dbName);
    byte[] buffer = new byte[1024];
    int length;
    InputStream myInput = mycontext.getAssets().open(dbName);
    while ((length = myInput.read(buffer)) > 0) {
        myOutput.write(buffer, 0, length);
    }

    myInput.close();
    myOutput.flush();
    myOutput.close();

}

my database in assets folder

0

There are 0 answers