I have made all the database and was working on emulator so injection of database was easy using the Android device monitor.
But in real device I have to programmatically copy it from the Assets folder to the app directory . And I have used so many codes and classes but I gets failed. Its look like Some of the code do copy the database file but the file remains empty .
Please suggest me the code which can copy the database file from the assets into the device with all the data it has in the database file saved in assets folder.
here I am using this file \
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
public class AssetDatabaseOpenHelper {
private static final String DB_NAME = "urdu.sqlite";
private Context context;
public AssetDatabaseOpenHelper(Context context) {
this.context = context;
}
public SQLiteDatabase openDatabase() {
File dbFile = context.getDatabasePath(DB_NAME);
if (!dbFile.exists()) {
try {
SQLiteDatabase checkDB = context.openOrCreateDatabase(DB_NAME, context.MODE_PRIVATE, null);
if(checkDB != null){
checkDB.close();
}
copyDatabase(dbFile);
} catch (IOException e) {
throw new RuntimeException("Error creating source database", e);
}
}
return SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READONLY);
}
private void copyDatabase(File dbFile) throws IOException {
InputStream is = context.getAssets().open(DB_NAME);
OutputStream os = new FileOutputStream(dbFile);
byte[] buffer = new byte[1024];
while (is.read(buffer) > 0) {
os.write(buffer);
}
os.flush();
os.close();
is.close();
}
}
Please tell me what I am doing wrong and why data is not being copied with the file that has been made in app directory. It is always empty. Please help me.
Note: I am using green Dao.