Logged in android user

Asked

Viewed 1,836 times

0

In my app, I need to change the menu between three types depending on the type of logged in user. As I do not yet have a bank 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 name of the user of the login screen to the home, but when changing screen the variable that has the name of the user and clears.

  • How do you do it? Could you show so someone can help?

  • This may help you. https://developer.android.com/training/basics/data-storage/shared-preferences.html?hl=pt-br

2 answers

1

How is it to test purposes (because there is no bank yet), you can create a Singleton by launching the application. This object stores static information, which means you can access it 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 app

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

This way, in any Activity your user will be "saved" in ram memory and will not disappear until the application is terminated.

0

Android offers many ways to store data from an application. One of this mode is called SharedPreferences, that allow you to store and retrieve data in key form. See 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.