Hazed 2.0
Hazed 2.0

Reputation: 133

Best way of maintaining a session in an android app after singing in?

I am making an app where as soon as you sign in, it will query into the database and retrieve your details, but what's the best way of storing these details as i change between activities without having to repeatedly query into the database again to retrieve them ?

I have tried using the intent.putExtra() method but it's causes NullPointerExceptions when i return to previous activities. Also putExtra() will not work on one of my classes which is HostApduService.

So what's the best method to maintian a session ? Will i need to use cookies or something ?

Upvotes: 1

Views: 127

Answers (1)

Tomas Jablonskis
Tomas Jablonskis

Reputation: 4376

SharedPreferences is what you are looking for.

A SharedPreferences object points to a file containing key-value pairs and provides simple methods to read and write them. Each SharedPreferences file is managed by the framework and can be private or shared.


How to use it:

Read data:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int value = sharedPref.getString("my_value_key", "default_value");

Write data:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
sharedPref.edit().putString("my_value_key", "my_value").apply();

You can read more about SharedPreferences here.

Good luck. :)

Upvotes: 2

Related Questions