0
I need to export my database to a text file. I’ve seen some questions like this around, but none with a cohesive or coherent answer.
Follows excerpt from my code:
//ACAO DO BOTAO CADASTRAR
public void Cadastrar (View view) {
//SALVO OS DADOS NO BANCO
SQLiteDatabase db = banco.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("nome", nome.getText().toString());
values.put("telefone", telefone.getText().toString());
values.put("email", email.getText().toString());
values.put("empresa", email.getText().toString());
values.put("obs", obs.getText().toString());
long resultado = db.insert("tab_clientes", null, values);
try {
//AQUI SERIA A PARTE DE EXPORTAR, MAS REALMENTE NÃO FAÇO IDEIA DE COMO FAZER
FileOutputStream ArqTexto = new FileOutputStream(Environment.getExternalStorageDirectory() + "/Clientes.csv");
Cursor cursor = db.query("tab_clientes", new String[]{"_id_cliente", "nome", "telefone", "email", "empresa", "obs"}, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
cliente = new HashMap<String, String>();
cliente.put("_id_cliente", cursor.getString(cursor.getColumnIndex("_id_cliente")));
cliente.put("nome", cursor.getString(cursor.getColumnIndex("nome")));
cliente.put("telefone", cursor.getString(cursor.getColumnIndex("telefone")));
cliente.put("email", cursor.getString(cursor.getColumnIndex("email")));
cliente.put("empresa", cursor.getString(cursor.getColumnIndex("empresa")));
cliente.put("obs", cursor.getString(cursor.getColumnIndex("obs")));
}
while (cursor.moveToNext());
}
catch (IOException e) {
Toast.makeText(this, "Erro", Toast.LENGTH_SHORT).show();
}
if (resultado != -1) {
Toast.makeText(this, "Cliente Cadastrado!", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "Erro ao Cadastrar!", Toast.LENGTH_SHORT).show();
}
}
Fledson, you could use the same instance of
SQLiteDatabase
and run this query, returning aCursor
where just iterate over the lines and mount your CSV. To run the query you can both use the methodquery
, as to therawQuery
, both return you oneCursor
.– Wakim
Great @Wakim I researched about what you suggested and I got this result. I updated the code. When compiling it does not present an error. Do you think it is correct? Now I don’t know how to write in the text file. I know through: Fileoutputstream Arqtext = new Fileoutputstream(Environment.getExternalStorageDirectory() + "/Clients.csv"); but what is the variable where the bank’s contents are? And how to write them?
– Fledson