I make this tutorial for a basic and a very used operation. There are many ways of exporting databases, but here i will explain a working and simple workaround.
Knowing the path to our database, it will be easy to copy that file to a SDCARD directory and then reverse.
So this will be our mission today.
I suppose that you have two buttons that handle this jobs: one for export, and another for import the database.
Attention importing will override the existent database, so you will need to add some warnings there.
Code for back-up database(copy file from database path to SDCARD path):
InputStream myInput; try { myInput = new FileInputStream("/data/data/com.packagename/databases/database_name");//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/some_folder"); // Create the folder if it doesn't exist: if (!directory.exists()) { directory.mkdirs(); } // Set the output file stream up: OutputStream myOutput = new FileOutputStream(directory.getPath()+ "/database_name.backup"); // 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(); } catch (FileNotFoundException e) { Toast.makeText(Main.this, "Backup Unsuccesfull!", Toast.LENGTH_LONG).show(); // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { Toast.makeText(Main.this, "Backup Unsuccesfull!", Toast.LENGTH_LONG).show(); // TODO Auto-generated catch block e.printStackTrace(); } Toast.makeText(Main.this, "Backup Done Succesfully!", Toast.LENGTH_LONG).show();
Code for importing this file again and override the database existing is:
OutputStream myOutput; try { myOutput = new FileOutputStream("/data/data/com.packagename/databases/database_name"); // Set the folder on the SDcard File directory = new File("/sdcard/some_folder"); // Set the input file stream up: InputStream myInputs = new FileInputStream(directory.getPath()+ "/database_name.backup"); // 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(); } catch (FileNotFoundException e) { Toast.makeText(Main.this, "Import Unsuccesfull!", Toast.LENGTH_LONG).show(); // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { Toast.makeText(Main.this, "Import Unsuccesfull!", Toast.LENGTH_LONG).show(); // TODO Auto-generated catch block e.printStackTrace(); } Toast.makeText(Main.this, "Import Done Succesfully!", Toast.LENGTH_LONG).show();