Copy the Android database into DB File -
- This is the easier of the two methods. I put a search in Google and found many queries and resolution for this.
- Basically what we do here is the SQLite Database creates .db file. this db file is copied as it is as a backup. We can use external SQLite readers in our PC to access the data.
- Code :
We create an class that extends AsyncTask so that export is handled in a thread.
/***************************************************************************************************************************************************************Export Database into file Class***************************************************************************************************************************************************************/class ExportDatabaseFileTask extends AsyncTask<String, Void, Boolean>{private final ProgressDialog dialog = new ProgressDialog(ctx);// can use UI thread here@Overrideprotected void onPreExecute(){this.dialog.setMessage("Exporting database...");this.dialog.show();}// automatically done on worker thread (separate from UI thread)protected Boolean doInBackground(final String... args){File dbFile = new File(Environment.getDataDirectory() +"/data/org.test.xyz/databases/excerDB.db");File exportDir = new File(Environment.getExternalStorageDirectory(), "");if (!exportDir.exists()){exportDir.mkdirs();}File file = new File(exportDir, dbFile.getName());try{file.createNewFile();this.copyFile(dbFile, file);return true;}catch (IOException e){Log.e("mypck", e.getMessage(), e);return false;}}// can use UI thread here@Overrideprotected void onPostExecute(final Boolean success){if (this.dialog.isShowing()){this.dialog.dismiss();}if (success){Toast.makeText(ctx, "Export successful!", Toast.LENGTH_SHORT).show();}else{Toast.makeText(ctx, "Export failed", Toast.LENGTH_SHORT).show();}}void copyFile(File src, File dst) throws IOException{FileChannel inChannel = new FileInputStream(src).getChannel();FileChannel outChannel = new FileOutputStream(dst).getChannel();try{inChannel.transferTo(0, inChannel.size(), outChannel);}finally{if (inChannel != null)inChannel.close();if (outChannel != null)outChannel.close();}}}
This function is called in the OnClick Button event
Context ctx = MainActivity.this;//Create a Button Listener for Export databaseButton impDBBtn = (Button) findViewById(R.id.imp_db_id);impDBBtn.setOnClickListener(new OnClickListener() {public void onClick(View view){try{new ExportDatabaseFileTask().execute("");}catch(Exception ex){Log.e("Error in MainActivity",ex.toString());}}});//Export Database into file Class
This is a very easy way of creating the backup of your App Data. But the diadvantage is that we need external database viewer to read the data.
If the data needs to be viewed then we need to use CSV Format which can be easily opened through Microsoft Excel.
References
Advertisement
[...] Comments « Android Database Table export to CSV – Part 2 [...]