2012-09-19 35 views
5

Cuando usa emulador, su archivo sqlite se almacena en una carpeta cercana a la carpeta principal de la aplicación y puede descargarlo. Pero esta característica no es accesible en dispositivos no rooteados. ¿Cómo puedo hacer una copia de seguridad de este archivo sqlite existente en la tarjeta SD programáticamente?¿Cómo puedo hacer una copia de seguridad del archivo sqlite en la tarjeta SD mediante programación?

Quiero tener un botón en mi aplicación que almacena este archivo en una ruta especial en mi tarjeta SD. ¿Es posible?

Gracias,

+0

pregunta similar aquí http://stackoverflow.com/questions/1995320/how- to-backup-database-file-to-sdcard-on-android –

+0

no dice cómo puede copiar la base de datos existente a la tarjeta sd – breceivemail

Respuesta

16

Puede probar esto, el trabajo para mí, recuerde para obtener el permiso WRITE_EXTERNAL_STORAGE en su manifiesto:

// Copy to sdcard for debug use 
    public static void copyDatabase(Context c, String DATABASE_NAME) { 
     String databasePath = c.getDatabasePath(DATABASE_NAME).getPath(); 
     File f = new File(databasePath); 
     OutputStream myOutput = null; 
     InputStream myInput = null; 
     Log.d("testing", " testing db path " + databasePath); 
     Log.d("testing", " testing db exist " + f.exists()); 

     if (f.exists()) { 
      try { 

       File directory = new File("/mnt/sdcard/DB_DEBUG"); 
       if (!directory.exists()) 
        directory.mkdir(); 

       myOutput = new FileOutputStream(directory.getAbsolutePath() 
         + "/" + DATABASE_NAME); 
       myInput = new FileInputStream(databasePath); 

       byte[] buffer = new byte[1024]; 
       int length; 
       while ((length = myInput.read(buffer)) > 0) { 
        myOutput.write(buffer, 0, length); 
       } 

       myOutput.flush(); 
      } catch (Exception e) { 
      } finally { 
       try { 
        if (myOutput != null) { 
         myOutput.close(); 
         myOutput = null; 
        } 
        if (myInput != null) { 
         myInput.close(); 
         myInput = null; 
        } 
       } catch (Exception e) { 
       } 
      } 
     } 
    } 
1

Puede probar siguiente código,

String path = Environment.getExternalStorageDirectory().toString() + "/path"; 
File folder = new File(path); 
if (!folder.exists()) 
{ 
    folder.mkdirs(); 
} 

File dbfile = new File(path + "/database.db"); 
if (!dbfile.exists()) 
{ 
    dbFile.createFile(); 
} 
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile, null); 
+0

esto no ** copia ** la base de datos existente. ** crea ** en esta ruta. – breceivemail

+0

@breceivemail según el título de su pregunta anterior ** ¿Cómo puedo almacenar el archivo sqlite en la tarjeta SD mediante programación? **, cumple los requisitos correctamente. – Lucifer

1

Usted puede intentar esto para copiar un archivo:

public void copyFile(File in, File out) { 
     String DialogTitel = getString(R.string.daten_wait_titel); 
     String DialogText = getString(R.string.kopiervorgang_laeuft); 
     try { 
      // Dialogdefinition Prograssbar 
      final ProgressDialog dialog = new ProgressDialog(this) { 
       @Override 
       public boolean onSearchRequested() { 
        return false; 
       } 
      }; 
      dialog.setCancelable(false); 
      dialog.setTitle(DialogTitel); 
      dialog.setIcon(R.drawable.icon); 
      dialog.setMessage(DialogText); 
      dialog.show(); 
      new Thread(new MyCopyThread(in, out)) { 
       @Override 
       public void run() { 
        try { 
         FileChannel inChannel = new FileInputStream(
           MyCopyThread.in).getChannel(); 
         FileChannel outChannel = new FileOutputStream(
           MyCopyThread.out).getChannel(); 
         try { 
          System.out.println("KOPIEREN"); 
          inChannel.transferTo(0, inChannel.size(), 
            outChannel); 
          if (inChannel != null) 
           inChannel.close(); 
          if (outChannel != null) 
           outChannel.close(); 
          setCopyError(false); 
         } catch (IOException e) { 
          setCopyError(true); 
          // throw e; 
         } finally { 
          if (inChannel != null) 
           inChannel.close(); 
          if (outChannel != null) 
           outChannel.close(); 
         } 
         dialog.dismiss(); 
         // Abschlussarbeiten 
         if (useExternalSD == true) { 
          // Externe DB 
          moveDBtoExternFinish(); 
         } else { 
          // Interne DB 
          moveDBtoInternFinish(); 
         } 
         moveDBFinishHandler.sendMessage(moveDBFinishHandler 
           .obtainMessage()); 
        } catch (Exception ex) { 

        } 
       } 
      }.start(); 
     } catch (Exception exx) { 

     } 

    } 

Este es el código para obtener el filname de su base de datos interna:

File interneDB = getApplicationContext().getDatabasePath(MY_DB_NAME); 

Reemplazar MY_DB_NAME con el nombre de su base de datos

Cuestiones relacionadas