What is the best method of using SharedPreferences?

0

I have an application with a webview in which it returns a Token when the user logs in. I need to save the user information to auto-login the next time it logs in, I plan to do this using the CheckBox. After researching a lot, I saw that the best thing to do is to store the Token, not the user and password, but what is the best way to do this? Thank you in advance!

    
asked by anonymous 16.02.2017 / 12:55

1 answer

0

The best way to store your Token is when the user is successfully connected, that is, when Token has already been successfully created. After that, just save Token .

For example, the user logged in to LoginActivity and was redirected to HomeActivity , then ...

  

Home Activity

public class HomeActivity extends Activity {
    SharedPreferences mPref = null;

    @Override
    public void onCreate (Bundle cicle) {
        super.onCreate(cicle);
        setContentView(R.layout.activity_home.xml); // Layout

        // SharedPreferences
        mPref = getSharedPreferences("tokenId", MODE_PRIVATE);
    }

    @Override
    public void onResume () {
        super.onResume();

        mPref.edit().putInt("tokenId", "9102887").apply();
    }
}
  

Login Activity

public class LoginActivity extends Activity {
    SharedPreferences mPref = null;

    @Override
    public void onCreate (Bundle cicle) {
        super.onCreate(cicle);
        setContentView(R.layout.activity_home.xml); // Layout

        // SharedPreferences
        mPref = getSharedPreferences("tokenId", MODE_PRIVATE);
    }

    @Override
    public void onResume () {
        super.onResume();

        // Se o token não for encontrado, o valor será 0
        int token = mPref.getInt("tokenId", 0);

        // Envia um pedido de token pro servidor
        // recebe o token e compara com o token salvo
        // se forem semelhantes, entra na conta direto
        int tokenServer = webS.getToken(deviceId, user, pass);

        if(token == tokenServer) // sucesso
    }
}

You do not necessarily need to save Token as Int . It was just an example, I think the recommended one for your case is String same. And it does not change much, just from putInt to putString . See the documentation .

Source : SharedPreferences

    
16.02.2017 / 13:26