我做了一个应用程序,在我的 SQLite 数据库中保存了一些信息。正如我们所知,SQLite 数据库驻留在设备的内部存储器中,它在安装应用程序时创建并在我们删除相应的应用程序时删除。
我正在发布应用程序的新版本,因此当我删除旧版本以安装新版本时,我丢失了保存在旧版本中的完整信息。
我的查询是我能否以某种方式从其 SQLite 数据库中检索旧版本的数据,以便可以在新版本中使用和维护它。
请建议我,这样我的用户就不会丢失他们的旧数据。
如果用户更新应用程序,那么数据库将保持不变。卸载旧版本并重新安装新版本会导致数据库被删除。
看我的评论,我真的不认为你需要担心它。
但是,如果您想备份和恢复您的数据库,以下方法会将其发送到 SD 卡,然后将其读回(在每种情况下都会覆盖以前存在的内容):
public void backup() {
try {
File sdcard = Environment.getExternalStorageDirectory();
File outputFile = new File(sdcard,
"yourDB.bak");
if (!outputFile.exists())
outputFile.createNewFile();
File data = Environment.getDataDirectory();
File inputFile = new File(data,
"data/your.package.name/databases/yourDB.sqlite");
InputStream input = new FileInputStream(inputFile);
OutputStream output = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
throw new Error("Copying Failed");
}
}
public void restore() {
try {
File sdcard = Environment.getExternalStorageDirectory();
File inputFile = new File(sdcard,
"yourDB.bak");
File data = Environment.getDataDirectory();
File outputFile = new File(data,
"data/your.package.name/databases/yourDB.sqlite");
if (!outputFile.exists())
outputFile.createNewFile();
InputStream input = new FileInputStream(inputFile);
OutputStream output = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
throw new Error("Copying Failed");
}
}