Share A Value Across All Views Of My Activity
Solution 1:
If its only a small information like "gender" i don't see much harm using "Static" variable(Ofcourse the static variable will become null if your app crashes when its in the background).
SharedPreference will come good if you want the information to be persistent(But i don't see you need this).
One more choice is you do can extend the application class to store the static data across activities.
Solution 2:
You could pass the gender to the next Activity with start activity Intent. Example:
Intent intent = newIntent(this, NEXT_ACTIVITY.class)
intent.putExtra("gender", genderVariable)
startActivity(intent);
And retrieve the value in NEXT_ACTIVITY class on onCreate() like this:
StringgenderVariable=""Bundleparms= getIntent().getExtras()
if (parms != null) genderVariable = parms.getString("gender")
Then, pass gender to all your views and persist the genderVariable on SharedPreferences or onSavedInstanceState bundle. I prefer onSavedInstanceState.
Hope it helps.
Solution 3:
I think there are many ways of which 4 I think are better. It ofcourse depends on what kind of data you want to store.
- For Lists or hashmaps, using a singleton class would be helpful.
- Using a static class would help, but might leak memory. You should be very careful and always check using logcat, MAT before releasing your app.
- Using preferences or database.
- Passing data as Intent extra (parcelable if needed).
Solution 4:
Using SharedPreferences would be the better way to share some global values across the application.
Post a Comment for "Share A Value Across All Views Of My Activity"