My app relies heavily on a database, which when the app is first opened should copy itself from the /assets/
folder to the database store. However, it seems to be incredibly temperamental: for example I have almost the exact same code in my free and paid versions yet one is currently working and the other isn't.
Would you guys please mind having a look at my code and seeing what is up/can be improved? My SQLiteOpenHelper
can be found here and the onCreate()
method of my DataProvider
is below:
@Override
public boolean onCreat开发者_StackOverflow社区e() {
dh = new DatabaseHelper(getContext());
try {
dh.createDataBase();
} catch (IOException ex) {
}
try {
dh.openDataBase();
} catch (SQLiteException ex) {
Toast.makeText(getContext(), "The database could not be copied\n" + ex.getMessage(),
Toast.LENGTH_LONG).show();
}
return true;
}
Thanks!
EDIT
After having a go with the emulator, I know that the database exists, but for some reason it just doesn't want to read it...
Below is code that I've used to copy databases (not sure if it could remedy the error or not, figured an alternate approach is always worth a shot). Otherwise, I don't see anything that's jumping out that could be causing an error.
void copyFile(File src, File dst) throws IOException {
FileChannel inChannel = new FileInputStream(src).getChannel();
FileChannel outChannel = new FileOutputStream(dst).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
Additional thought, why open and close the database when checking to see if it exists. Seems you could get away with something like this:
private boolean checkDataBase() {
String myPath = DB_PATH + DB_NAME;
return new File(myPath).exists();
}
You shouldn't really be hardcoding the path to the databases directory. Instead of building myPath everytime you need it try constructing in the contructor with the following code:
Instance:
private File myPath;
And in constructor:
myPath = context.getDatabasePath(DB_NAME);
精彩评论