I am developing an Android that uses a database. I want to copy the database to the SD card when use true machine run. But it doesn’t always succeed. My program doesn’t say why, only that it can’t copy the database. I store the database in res\raw\mobilephone1.db; it’s 10 MB. I set the permissions to allow writing data to the SD card.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>
Is this right?
private final String DATABASE_PATH = android.os.Environment
.getExternalStorageDirectory().getAbsolutePath()
+ "/mobilephone";
private final String DATABASE_FILENAME = "mobilephone.db";
private SQLiteDatabase openDatabase()
{
try
{
// obtain absolute path of mobilephone.db
String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME;
File dir = new File(DATABASE_PATH);
// if/sdcard/mobilephone exist,crtate this list
if (!dir.exists()) {
dir.mkdir();
}
// if mobilephone.db file did not exist in/sdcard/mobilephone then copy this filt to SD card list(/sdcard/mobilephone) from res\raw
if (!(new File(databaseFilename)).exists())
{
// obtain the InputStream object that encapsulate mobilephone.db
InputStream is = getResources().openRawResource(R.raw.mobilephone1);
FileOutputStream fos = new FileOutputStream(databaseFilename);
int count = 0;
while (count == 0) {
count = is.available();
}
byte[] buffer = new byte[count];
int readCount = 0; // the number of bytes that has successfully readen
while (readCount < count) {
readCount += is.read(buffer, readCount, count - readCount);
}
fos.write(buffer, 0, count);
fos.close();
is.close();
}
// go to mobilephone.db in /sdcard/mobilephone
SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(
databaseFilename, null);
return database;
}
catch (Exception e)
{
}
return null;
}
Try this one out ::
Also you need only one permission :