User logged in android

0

In my app, I need to change the menu between three types depending on the type of user logged in. Since I do not yet have a database to verify this information, I would like to know if there is any way to store this user name to display the correct menu type.

Today I can already pass the username of the login screen to the home, but when changing the screen the variable that has the name of the user and clean.

    
asked by anonymous 02.09.2016 / 13:11

2 answers

1

As it is for test purposes (because you do not yet have a database), you can create a Singleton when you start the application. This object stores static information, which means that you can access from anywhere in the application.

    public class SingletonUsuario {

        private static SingletonUsuario instance = null;
        private static Usuario usuario = null;

        public static SingletonUsuario getInstance() {
            if (instance == null) {
                usuario = new Usuario();
                return instance = new SingletonUsuario();
            } else {
                return instance;
            }
        }

    public void setUsuario(Usuario usuario) {
        SingletonUsuario.usuario = usuario;
    }

    public Usuario getUsuario() {
        return SingletonUsuario.usuario;
    }
}

To use it, just call:

Usuario u = new Usuario();
u.setNome("Joãozinho");
SingletonUsuário.getInstance.setUsuario(u);

To get the information from anywhere in the application

txtView.setText(SingletonUsuario.getInstance.getUsuario.getNome); // retorna a string nome

In this way, in any activity your user will be "saved" in the ram and will not disappear until the application is closed.

    
02.09.2016 / 16:28
0

Android offers many ways to store data in an application. One of these is called SharedPreferences , which allow you to save and retrieve data in key form . Here's an example:

public static final String PREFS_NAME = "USUARIO";
SharedPreferences  settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);

To recover the value you use:

settings.getString(PREFS_NAME, "")

Details

02.09.2016 / 14:29