dimanche 31 mai 2015

How to copy Database from assets folder to /data/data/ folder android device

i have a class, it import database.sql from assets folder into /data/data/ of my phone , but i can't find that database in data/data folder. maybe i have a mistake. this is my code : SQLiteDBHelper.java

public class SQLiteDBHelper extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;

private static final String DB_NAME = "DATABASE_VIETNAM.sqlite";
private static final String DB_PATH = "/databases/";
static Context ctx;
public SQLiteDBHelper(Context context) {
    super(context, DB_NAME, null, DATABASE_VERSION);
    ctx = context;
}
public void CopyDataBaseFromAsset() throws IOException{

    InputStream myInput = ctx.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = getDatabasePath(); 
// if the path doesn't exist first, create it 
File f = new File(ctx.getApplicationInfo().dataDir + DB_PATH);
    if (!f.exists())
        f.mkdir(); 
// Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0) {
        myOutput.write(buffer, 0, length);
    } 
// Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();
}
private static String getDatabasePath() {
    return ctx.getApplicationInfo().dataDir + DB_PATH
            + DB_NAME;
}
public SQLiteDatabase openDataBase() throws SQLException{
    File dbFile = ctx.getDatabasePath(DB_NAME);
    if (!dbFile.exists()) {
        try {
            CopyDataBaseFromAsset();
            System.out.println("Copying sucess from Assets folder");
        } catch (IOException e) {
            throw new RuntimeException("Error creating source database", e);
        }
    }

    return SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS |
            SQLiteDatabase.CREATE_IF_NECESSARY);
}
@Override
public void onCreate(SQLiteDatabase db) {

}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }
}

how can i fix it?

Aucun commentaire:

Enregistrer un commentaire