Android: restaurar la base de datos borra la base de datos cuando falta el archivo de la base de datos
Frecuentes
Visto 1,414 veces
1
He encontrado un tutoriales que copia la base de datos en una carpeta como copia de seguridad y la vuelve a copiar en la carpeta de la base de datos de la aplicación como restauración. Casi todo funciona bien, excepto por una cosa: cuando elimino el archivo .db respaldado de mi carpeta y hago clic en Restaurar en mi aplicación, busca el archivo, no puede encontrarlo, luego sobrescribe toda la base de datos sin nada. Es como si vaciara toda la base de datos.
Apoyo:
try {
InputStream myInput;
OutputStream myOutput;
myInput = new FileInputStream("/data/data/com.me.myapp/databases/HotOrNotdbLists2");//this is
// the path for all apps
//insert your package instead packagename,ex:com.mybusiness.myapp
// Set the output folder on the SDcard
File directory = new File("/sdcard/MyApp/");
// Create the folder if it doesn't exist:
if (!directory.exists())
{
directory.mkdirs();
}
// Set the output file stream up:
myOutput = new FileOutputStream(directory.getPath()+
"/myapp.db");
// Transfer bytes from the input file to the output file
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0)
{
myOutput.write(buffer, 0, length);
}
// Close and clear the streams
myOutput.flush();
myOutput.close();
myInput.close();
Toast.makeText(Settings.this, "Backup done successfully!", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
Toast.makeText(Settings.this, "Backup unsuccessful! File cannot be created! Directory does not exist?", Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(Settings.this, "Backup unsuccessful!", Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
e.printStackTrace();
}
Restaurar:
OutputStream myOutput;
try {
myOutput = new FileOutputStream("/data/data/com.me.myapp/databases/HotOrNotdbLists2");
// Set the folder on the SDcard
File directory = new File("/sdcard/MyApp/");
// Set the input file stream up:
InputStream myInputs = new FileInputStream(directory.getPath()+ "/myapp.db");
// Transfer bytes from the input file to the output file
byte[] buffer = new byte[1024];
int length;
while ((length = myInputs.read(buffer))>0)
{
myOutput.write(buffer, 0, length);
}
// Close and clear the streams
myOutput.flush();
myOutput.close();
myInputs.close();
Toast.makeText(Settings.this, "Restore done successfully!", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
Toast.makeText(Settings.this, "Restore unsuccessful! File not found! Directory does not exist?", Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) { Toast.makeText(Settings.this, "Restore unsuccessful!",
Toast.LENGTH_SHORT).show();
// TODO Auto-generated catch block
e.printStackTrace();
}
Editar: Agregué la respuesta de Jason y aún borra la base de datos, incluso si obtengo false al directorio B y obtener el ¡Restaurar sin éxito! ¡Archivo no encontrado! ¿El directorio/archivo no existe? mensaje ???!?!
try {
OutputStream myOutput;
myOutput = new FileOutputStream("/data/data/com.me.myapp/databases/HotOrNotdbLists2");
// Set the folder on the SDcard
File directory = new File("/sdcard/MyApp/");
boolean directoryB = new File("/sdcard/MyApp/", "/myapp.db").exists();
Toast.makeText(Settings.this, "directoryB: " + directoryB, Toast.LENGTH_SHORT).show();
if (directoryB == true)
{
Toast.makeText(Settings.this, "File exists!", Toast.LENGTH_SHORT).show();
// Set the input file stream up:
InputStream myInputs = new FileInputStream(directory.getPath()+ "/myapp.db");
// Transfer bytes from the input file to the output file
byte[] buffer = new byte[1024];
int length;
while ((length = myInputs.read(buffer))>0)
{
myOutput.write(buffer, 0, length);
}
// Close and clear the streams
myOutput.flush();
myOutput.close();
myInputs.close();
Toast.makeText(Settings.this, "Restore done successfully!", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(Settings.this, "Restore unsuccessful! File not found! Directory/file does not exist?", Toast.LENGTH_SHORT).show();
}
} catch (FileNotFoundException e) {
//Toast.makeText(Settings.this, "Restore unsuccessful! File not found! Directory does not exist?", Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) { Toast.makeText(Settings.this, "Restore unsuccessful!",
Toast.LENGTH_SHORT).show();
// TODO Auto-generated catch block
e.printStackTrace();
}
1 Respuestas
1
Compruebe si el archivo existe primero antes de continuar con la operación de restauración, así:
new File(directory, "/myapp.db").exists()
FileInputStream
creará archivos automáticamente si no existen.
contestado el 02 de mayo de 12 a las 19:05
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas android sqlite or haz tu propia pregunta.
Lo intenté, todavía sobrescribe la aplicación. Creo que la condición está bien, ¿alguna idea? Actualicé la publicación principal: erdomestre
Mueva su cheque a la parte superior del método, para que no ejecute nada si el archivo no existe. Agregue algunos registros también para ver si el archivo existe o no (puede ser el caso de que el archivo no se elimine realmente). - jason robinson