考虑到我的应用程序仍在开发中,有时会出现错误,这会影响我与应用程序连接的数据库。因为我已经测试了数据,所以每次出错都不想输入,我想实现一个简单的导入/导出功能。
我最近偶然发现this问题,这或多或少是我想要的。我告诉你我的代码实现了。导出功能工作正常,我可以使用来自android市场的SQLIte Database
应用程序进行测试。问题是导入。它告诉我Toast
,一切都很顺利,但没有任何反应。不过,我不太确定我是否做得对。
在MainMenuActivity
我实施了以下方法:
(...)
public boolean onCreateOptionsMenu(Menu menu){
menu.add(1, Menu.FIRST, Menu.FIRST, "backup DB").setIcon(R.drawable.ic_action_save);
menu.add(1, Menu.FIRST+1, Menu.FIRST+1, "import DB").setIcon(R.drawable.ic_action_upload);
return super.onCreateOptionsMenu(menu);
}
(...)
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case 1:
backupDatabase();
return true;
case 2:
importDatabase();
return true;
default:
break;
}
return super.onOptionsItemSelected(item);
}
private void backupDatabase(){
try{
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//challenge.main//databases//DBCHALLENGES";
String backupDBPath = "DBCHALLENGES";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getBaseContext(), "Successfully backed up database!", Toast.LENGTH_LONG).show();
}
}catch (IOException e){
Toast.makeText(getBaseContext(), "Error in backing up database!", Toast.LENGTH_LONG).show();
}
}
private void importDatabase(){
datasource = new CustomDataSource(this);
datasource.open();
try{
datasource.importDatabase("DBCHALLENGES");
Toast.makeText(getBaseContext(), "Successfully imported database!", Toast.LENGTH_LONG).show();
}catch (IOException e){
Toast.makeText(getBaseContext(), "Error in importing database!", Toast.LENGTH_LONG).show();
}finally{
datasource.close();
}
}
在CustomDataSource
:
public boolean importDatabase(String dbPath) throws IOException{
return dbHelper.importDatabase(dbPath);
}
最后在DBHelper
扩展SQLiteOpenHelper
public boolean importDatabase(String dbPath) throws IOException{
close();
File newDB = new File(dbPath);
File oldDB = new File("//data//challenge.main//databases//DBCHALLENGES");
if(newDB.exists()){
FileUtils.copyFile(new FileInputStream(newDB), new FileOutputStream(oldDB));
getWritableDatabase().close();
return true;
}
return false;
}
但是,按下导入Button
,会显示正Toast
,表示导入成功。但我之前空的申请仍然是空的。备份数据库应该位于内部存储的第一级,它的作用。我想,也许我对这些路径感到困惑,但我无法完全了解它。
答案 0 :(得分:2)
试试这个:
private void importDatabase(String inputFileName) throws IOException
{
InputStream mInput = new FileInputStream(inputFileName);
String outFileName = YOUR_DB_PATH_HERE;
OutputStream mOutput = new FileOutputStream(outFileName);
byte[] mBuffer = new byte[1024];
int mLength;
while ((mLength = mInput.read(mBuffer))>0)
{
mOutput.write(mBuffer, 0, mLength);
}
mOutput.flush();
mOutput.close();
mInput.close();
}