-1

How can I make data available through my whole android app? For instance, I want to display a user picture in the toolbar in every screen. Also, the name of the user is displayed in the navigation drawer in every screen.

Is a singleton the right approach for this? Or are other techniques better?

I have been googling a lot, but i can't find a good approach for my use case so far.

Peter van Leeuwen
  • 938
  • 1
  • 9
  • 17

1 Answers1

2

To use shared preferences:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();

to save in shared preferences:

editor.putString("tag", "save me please");
editor.apply();

to retrieve from shared preferences:

String s = preferences.getString("tag", "default_value");

Notes: You can make your tags as string constants to make sure you are always using the same value. If you use the editor for multiple values, always remember to add editor.apply() in the end, to actually apply your changes. If you want the editor to write the changes synchronously, use editor.commit() instead. You can save any type of variable in the shared preferences, just use the appropriate method (instead of putString use putInt, putLong, etc - same with the getSring). More on Shared Preferences in the API here

Nikos Hidalgo
  • 3,666
  • 9
  • 25
  • 39
  • Does this also apply for the use case I described above? I need to display images in the toolbar and navigation drawer and the name of the user. All those widgets are there in every screen of the app. – Peter van Leeuwen Nov 15 '18 at 20:02
  • yes, you can use putString for the user's name, and the path of the user's photo. Then have a method that will read the strings from the shared preferences and populate your views at the toolbar/navigation drawer – Nikos Hidalgo Nov 15 '18 at 20:05
  • oke, but the image is retrieved from an online location. This means it needs to be downloaded every time the screen is loaded right? So how I can download and store it once and retrieve it from that location every next time? – Peter van Leeuwen Nov 15 '18 at 20:07
  • after you download it, you use the local path in the shared preferences as described above – Nikos Hidalgo Nov 15 '18 at 20:10
  • Oke, thanks. Do you think a singleton (which I am currently using) that contains all such data is not a good approach? – Peter van Leeuwen Nov 16 '18 at 08:26
  • I haven't been using singletons much. Only when I need to make sure that I get unique instances of classes, so someone else could be of more help. – Nikos Hidalgo Nov 16 '18 at 09:19