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

Question:

I have an application that saves form data in a SQLite database table. Until now, I only consulted this data within the application, without any problems.

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 opening the text file, it would display the data that were registered: joao;12345678 maria;98765432

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

Answer:

I'm not sure what your database structure looks like exactly, but since you can already read this data, my suggestion goes from there.

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

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

And so, here's an example method that takes 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);
        outputStream.write(strToSave.getBytes());
        outputStream.close();
    } catch (Exception e) {
        Log.e("SAVE_FILE", e.getMessage());
    }
}

This method you need to run in a different thread, so it's recommended to use it inside an AsyncTask .

With that, you'll get the pessoas.txt , which you can use with it as needed, whether to send it by email, share it or simply read it afterwards. More details, you can see here .

Scroll to Top