When I'm trying to copy my SQLite database from assets foder, my application crashes. Following code works fine in Eclipse on similar projects but not in Android Studio. If someone had same issue please tell me what I'm doing wrong. Thanks.
Here's logs:
E/log﹕java.io.FileNotFoundException:weather_app_db.sqlite E/AndroidRuntime﹕ FATAL EXCEPTION: main java.lang.Error: Error copying database at com.example.user.weatherapp.db.DataBaseHelper.createDataBase(DataBaseHelper.java:54)`
My code:
public class DataBaseHelper extends SQLiteOpenHelper
{
private static String TAG = "DataBaseHelper"; // Tag just for the LogCat window
private static String DB_NAME ="weather_app_db.sqlite";// Database name
private static String DB_PATH;
private SQLiteDatabase mDataBase;
private final Context mContext;
public DataBaseHelper(Context context)
{
super(context, DB_NAME, null, 1);
this.mContext = context;
if(android.os.Build.VERSION.SDK_INT >= 4.2){
DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
}
else
{
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
}
}
public void createDataBase() throws IOException{
//If database not exists copy it from the assets
boolean mDataBaseExist = checkDataBase();
if(!mDataBaseExist){
this.getReadableDatabase();
try{
copyDataBase();
}
catch (IOException e){
Log.e("log",e.toString());
throw new Error("Error copying database"); //line 54
}
}
}
//Check that the database exists
private boolean checkDataBase()
{
File dbFile = new File(DB_PATH+DB_NAME);
Log.v("dbFile", dbFile + " "+ dbFile.exists());
return dbFile.exists();
}
//Copy the database from assets
private void copyDataBase() throws IOException{
String outFileName = DB_PATH+DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
InputStream myInput = mContext.getAssets().open(DB_NAME);
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
...
}
Here's my assets directory:
Aucun commentaire:
Enregistrer un commentaire