oetzi
oetzi

Reputation: 97

Android: How to access data across all Activites?

I am searching for a possibility to store the user ID (received after login) in a way that all Activites have access to it.
If I understood it correctly a SharedPreference is only available for one specific Acitivty.

Which possibilites do I have to save the ID comprehensively?

Greetings, oetzi

Upvotes: 0

Views: 116

Answers (3)

Lukas Knuth
Lukas Knuth

Reputation: 25755

  • Option 1: Create a singleton to hold your data (preferred)
  • Option 2: Override Application and access the data using the context

Those are for application states which will be non-persistent, meaning that they're stored in memory and therefor will be lost, as soon as your application quits.

For persistent storage, use one of those.

For more ideas, see the Storage Options article from the Android Docs.

Upvotes: 2

fweigl
fweigl

Reputation: 22018

The SharedPreferences are accessible throughout you whole application. If you only need to store the data only for the runtime of the app, just declare it public static and you can access it from anywhere.

Upvotes: 0

Carnal
Carnal

Reputation: 22064

To put data:

SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("user_id", "THE USER ID HERE");
editor.commit();

To retrieve data:

SharedPreferences prefs = getPreferences(MODE_PRIVATE); 
String userID = prefs.getString("user_id", null);

If the user id is a number you can use putInt or whatever the primitive data is.

Upvotes: 0

Related Questions