How to save a SQLite database table to a text file on Android?


I have an application that saves the data of a form in a SQLite database table. So far, I've only been querying these data within the application, no problem.

Example: My form saves information such as name and phone number. This information is stored in an SQLite database. I would like to create a button to, when clicked, generate a text file with the database information. When you open the text file, it would display the data that has been logged: joao; 12345678 maria; 98765432

But now I need to save this database into a text file. The app is for Android and I'm using Android Studio. If so, how do I do it?

asked by anonymous 16.04.2015 / 14:17

2 answers


I do not know how exactly your database structure is, but since you can already read this data, my suggestion goes from this point on.

First, you need the write permission, which you should include in your Manifest file:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

And so, here is an example method that receives a list of Pessoa and saves the name and phone information. This is where you will replace and use the way you read this data from your bank:

private void salvarArquivoPessoas(List<Pessoa> lista) {
    String filename = "pessoas.txt";
    StringBuffer sb = new StringBuffer();

    for (Pessoa pessoa : lista) {
        sb.append(pessoa.getNome() + ";" + pessoa.getTelefone() + "\n");

    String strToSave = sb.toString();
    FileOutputStream outputStream;

    try {
        outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
    } catch (Exception e) {
        Log.e("SAVE_FILE", e.getMessage());

This method you need to run on a different thread, so it's recommended to use within a % with_% / a>.

With this, you will get the AsyncTask file, which with it you use according to your need, either to send by email share or simply read next. More details, you can see here .

16.04.2015 / 14:52

You should use AssyncTask for this type of operation.

Nearly complete code here

16.04.2015 / 14:47