1

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 ?

Nico Haase
  • 11,420
  • 35
  • 43
  • 69
Hazed 2.0
  • 133
  • 2
  • 14
  • 3
    Possible duplicate of [How to maintain session in android?](https://stackoverflow.com/questions/20678669/how-to-maintain-session-in-android) – Uzair A. Jul 30 '18 at 03:38
  • you can store all the details in SharedPreferences, so that you can access those data from any activity – Aan Jul 30 '18 at 03:38
  • You can use this library to remove boilerplate code of sharedpreferences. https://github.com/moinkhan-in/PreferenceSpider – Moinkhan Jul 30 '18 at 12:20

1 Answers1

2

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. :)

Tomas Jablonskis
  • 4,246
  • 4
  • 22
  • 40