3
I’m having trouble using files on android.
Save the file and use quietly until close the application, when I open the app again the file is recreated and I lose the recorded data.
I have tested several solutions, I have this code now:
public class PersistenciaSerial {
String arquivo;
Context cont;
File fileDir;
public PersistenciaSerial(Context context, String fileName) {
cont = context;
fileDir = new File(Environment.getExternalStorageDirectory().getPath()+"/saude");
if(fileDir.isDirectory()){
fileDir.mkdirs();
} else {
Log.e("Diretório já existente", fileDir.getName());
}
arquivo = fileDir+"/"+fileName;
}
public Object pegarObjeto() {
Object lista = null;
//Classe responsavel por recuperar os objetos do arquivo
try {
FileInputStream fileInputStream = cont.openFileInput(arquivo);
Log.e("Teste de fileinputstream", fileInputStream.toString());
ObjectInputStream objLeitura = new ObjectInputStream(fileInputStream);
lista = (Object)objLeitura.readObject();
objLeitura.close();
objLeitura.close();
Log.e("Teste OFF Pegando", String.valueOf(lista));
}catch (Exception e){
Log.e("Teste Pegando False", e.toString());
}
return lista;
}
public void persistir(Object listaEntrada) {
//Classe responsavel por inserir os objetos
try {
Log.e("Teste OFF Persistindo", "Persistindo");
FileOutputStream fileOutputStream = cont.openFileOutput(arquivo, 1);
Log.e("Teste de fileoutputstream", fileOutputStream.toString());
ObjectOutputStream objGravar = new ObjectOutputStream(fileOutputStream);
//Grava o objeto cliente no arquivo
objGravar.writeObject(listaEntrada);
objGravar.flush();
Log.e("Teste OFF Persistindo", arquivo);
Log.e("Teste OFF Persistindo", String.valueOf(listaEntrada));
}catch (Exception e){
Log.e("Teste Persistindo False", e.toString());
}
}
}
I put the whole class out of desperation.
I already thank you for your time dedicated to my doubt.
I couldn’t use Context.MODE_APPEND, only I can’t remember why. Now put and passed the storage to internal but when the app is terminated, the data is lost in the same way.
– Rhuan Frank
I can find no reason for this to happen. Please note that each time you install the application the data is lost. During development whenever you make a change to the program the application is uninstalled and then installed with the changes.
– ramaral