I have an external sqlite database called example.db that I'm trying to a create with OrmLite. I made some searchs on internet and everybody recommended this tutorial http://ift.tt/19PBhQ1
So I followed it and worked well, but when I tried to do the same using OrmLite I couldn't create my own database from external file (example.db). I found out when I call the method createDatabase(), the database is already created and it didn't occur when I was using OpenHelperDatabase without OrmLite.
Does anybody have any idea?
The code is:
//imports
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static String DB_PATH = "/data/data/com.example/databases/";
private static String DB_NAME = "example";
private static final int DATABASE_VERSION = 1;
private SQLiteDatabase exampleDB;
private final Context context;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DATABASE_VERSION);
this.context = context;
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if(dbExist){
Log.i(DatabaseHelper.class.getName(), "Database already exist!!! Here is the problem");
}else{
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_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;
}
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = context.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
//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();
}
@Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
Log.i(DatabaseHelper.class.getName(), "onCreate");
try {
createDataBase();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
//TODO
}
@Override
public synchronized void close() {
if(exampleDB != null)
exampleDB.close();
super.close();
}
}
Aucun commentaire:
Enregistrer un commentaire