我正在尝试在android studio应用程序中导入一个sqlite数据库..我已经在我的设备内存中进行了备份...当我尝试在我的应用程序中导入数据库时,导致消息导入失败。请帮我导入我的db在我的应用程序中
我在文件夹中进行了备份:dbname.db
private void importDB() {
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
System.out.println("KKKKKKKKKKKKKKKKKKKKKK");
String currentDBPath = "//data//" + getPackageName() + "//databases//" +"dbname.db" ;
String backupDBPath = "Restore.db"; // From SD directory.
System.out.println("HHHHHHHHHHHHHHHHHHHHHHH");
File backupDB = new File(data, currentDBPath);
File currentDB = new File(sd, backupDBPath);
System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAaa");
FileChannel src = new FileInputStream(backupDB).getChannel();
FileChannel dst = new FileOutputStream(currentDB).getChannel();
dst.transferFrom(src, 0, src.size());
System.out.println("FFFFFFFFFFFFFFFFFFFFFFFFFFFFH");
src.close();
dst.close();
Toast.makeText(getApplicationContext(), "Import Successful!",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Import Failed!", Toast.LENGTH_SHORT)
.show();
}
}
答案 0 :(得分:2)
请按照以下步骤解决恢复SQlite DB
创建LinnaeusDatabase类:
public class LinnaeusDatabase extends SQLiteOpenHelper {
private static String DATABASE_NAME = "Dragonfly.db";
public final static String DATABASE_PATH =
"/data/data/com.kan.linnaeus/databases/";
private static final int DATABASE_VERSION = 1;
private SQLiteDatabase dataBase;
private final Context dbContext;
public LinnaeusDatabase(Context context) {
super(context, DBActivity.DatabaseName, null, DATABASE_VERSION);
this.dbContext = context;
DATABASE_NAME = DBActivity.DatabaseName;
// checking database and open it if exists
if (checkDataBase()) {
openDataBase();
} else {
try {
this.getReadableDatabase();
copyDataBase();
this.close();
openDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
Toast.makeText(context, "Initial database is created", Toast.LENGTH_LONG).show();
}
}
private void copyDataBase() throws IOException {
InputStream myInput = dbContext.getAssets().open(DATABASE_NAME);
String outFileName = DATABASE_PATH + DATABASE_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException {
String dbPath = DATABASE_PATH + DATABASE_NAME;
dataBase = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
boolean exist = false;
try {
String dbPath = DATABASE_PATH + DATABASE_NAME;
checkDB = SQLiteDatabase.openDatabase(dbPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
Log.v("db log", "database does't exist");
}
if (checkDB != null) {
exist = true;
checkDB.close();
}
return exist;
}
}