I'm making an simple login app in Android Studio, and I dont want to use any data base to store the credentials of the users.
I tried to make an Object File inside the app, and in this storage a HashMap with all the users.
I made that with the following code:
File archivo_users = new File("Users.bixa");
if (!archivo_users.exists()){
try {
ObjectOutputStream admin = new ObjectOutputStream( openFileOutput(archivo_users.toString(), Activity.MODE_PRIVATE));
HashMap<String, Usuario> admin_user = new HashMap<>();
// Make an Hash Map with a 'admin' default user
admin_user.put("admin",new Usuario("admin","admin","admin","admin",'h'));
admin.writeObject(admin_user);
admin.close();
} catch (IOException e) {
Toast.makeText(this,"An error ocurred creating Users.bixa",Toast.LENGTH_LONG).show();
}
After that, I read the file and make an static variable for enter to the data in all the app:
try {
ObjectInputStream baseDatos_usuarios = new ObjectInputStream(openFileInput(archivo_users.toString()));
UsuariosRegistrados = (HashMap<String,Usuario>) baseDatos_usuarios.readObject();
baseDatos_usuarios.close();
} catch (IOException | ClassNotFoundException e) {
// Muestra ventana emergente en la app con el mensaje de la excepcion
Toast.makeText(this,"Error al intentar leer la base de Usuarios",Toast.LENGTH_LONG).show();
}
Then, in my register activity, when the user introduce correctly all the data, I update the file this way:
BienvenidaActivity.UsuariosRegistrados.put(username,new Usuario(username, contrasenia, nombre, apellido, genero));
try {
ObjectOutputStream archivo = new ObjectOutputStream( openFileOutput("Usuarios.bixa", Activity.MODE_PRIVATE));
archivo.writeObject(BienvenidaActivity.UsuariosRegistrados);
archivo.close();
} catch (IOException e) {
Toast.makeText(this,"ERROR: No se logro actualizar la base de datos",Toast.LENGTH_LONG).show();
}
All of this works perfectly, but the problem is that when I close the app, the File dosen't conteins the new users, I dont now if the File is deleted when the app is closed or if my conditional of the firts code is wrong and always creates a new file.
Hope someone can help me, and thanks for the time if you read this. Note: Sorry if I wrote something wrong, my native language is spanish.
question from:
https://stackoverflow.com/questions/65874754/how-avoid-a-file-created-inside-an-app-gets-deleted-when-it-get-closed