Which method to use Sharedpreferences best?

Asked

Viewed 304 times

0

I have an application with a webview in which a token returns when the user logs in. I need to save the user information to perform the auto-login the next time he logs in, I intend to do so using Checkbox. After a lot of research, 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? Thanks in advance!

  • Do you doubt that you do not know how to use Sharedpreferences to write the Token? Or do you know how to use it but the problem is to use it in this context?

  • I know how to use, I saw some examples recording user and pass and I was able to play, but I couldn’t fit into the context of Token, and I couldn’t find many examples

1 answer

0


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

For example, the user connected to LoginActivity and was redirected to the 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 don’t need necessarily save the Token as Int. It was just an example, I believe the recommended for your case is a String same. And it doesn’t change much, just putInt for putString. See on documentation.

Source: Sharedpreferences

  • I managed to understand the context, I will try to reproduce, thanks!

Browser other questions tagged

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