java – Android – How to export the database into a csv file?

Question:

I have an application that collects and stores information in a database, and the user can consult this data within the application itself. However, I would like to insert a button to export the database into a .csv file.

Has anyone done or seen and tested an example where it really works? I found several attempts on StaCkOverFlow gringo, as well as on some other sites, but none that worked.

I am using Android Studio.

Answer:

Below is the solution I implemented.

1- Include opencsv.jar in the project

two-

 private boolean criaCsv(String select, long parametro, String nomeArquivoCsv) throws Exception
        {
            try{                
                File arquivoCsv =  new File( caminho + nomeArquivoCsv );
                arquivoCsv.createNewFile();
                CSVWriter writer = new CSVWriter(new FileWriter(arquivoCsv), CSVWriter.DEFAULT_SEPARATOR);
                Boolean includeHeaders = false;

                PreparedStatement ps = getConnection().prepareStatement(select, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
                ps.setFetchSize(FETCH_BD);
                ps.setLong(1, parametro);

                ResultSet resultSet = (ResultSet) ps.executeQuery();
                writer.writeAll(resultSet, includeHeaders);
                writer.flush();
                writer.close();

                return true;
            }
            catch(Exception e){
                log.error("",e);
                return false;
            }
        }


public Connection getConnection()
    {
        try
        {
            if( conn == null || conn.isClosed()){

                conn = dataSource.getConnection();
                conn.setAutoCommit(false);
            }
        } catch (SQLException e)
        {
            log.error("", e);
        }

        return conn;
    }
Scroll to Top