How to save an Sqlite database table to a text file on Android?

Asked

Viewed 2,124 times

3

I have an application that saves data from a form in an Sqlite database table. Until now, just consult this data within the application, no problems.

Example: My form saves information such as name and phone. This information is stored in a 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 was captured: 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, as I do?

  • When you say "save that database", what exactly do you mean? How will this file be disposed of? Describe this question better, so we can help more punctually.

  • @Paulorodrigues Hello Paul, I edited the question. I hope it’s clearer now. Thank you.

2 answers

1

I don’t know how exactly your database structure looks, but since you can already read this data, my suggestion goes from this point.

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

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

And then, here’s an example of a method that gets 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 database:

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 is recommended to use within a AsyncTask.

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

  • Thank you Paulo! I will test!

0

  • Avoid referencing external links (they may break in the future). Copy the content to use your own question and cite the source.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.