Reputation: 3010
In my Android application, when i login to the application, i receive a set of strings which i'm saving using Shared Preferences
.
These strings are nothing but the text that must be assigned to the TextView's
, hints for the EditText's
etc. throughout the application.
Eg. Say my application has 4 activities. Each activity has say 10 labels/TextViews. So totally on login i'll be receiving 40 strings and i'm storing it in shared preferences based on some logic. My question is is there a way i can have 40 strings declared somewhere and initialized on login (instead of storing in Shared Preferences). And i must be able to use this strings throughout my application? Which is the best way to achieve this?
Thanks in advance.
Upvotes: 0
Views: 83
Reputation: 5940
You can achieve this by extending android.app.Application
public class MyApplication extends Application {
private HashMap<String, String> variables = new HashMap<>();
public String getVariable(String key) {
return variables.get(key);
}
public void setVariable(String key, String value) {
variables.put(key, value);
}
}
and in manifest
<application
android:name="MyApplication"
android:icon="@drawable/icon"
android:label="@string/app_name">
....
</application>
and do this in your activity where you want to get the variable
// set variable
((MyApplication) this.getApplication()).setVariable("key1", "value1");
// get variable
String value1 = ((MyApplication) this.getApplication()).getVariable("key1");
Upvotes: 2
Reputation: 3913
android.app.Application:
Base class for those who need to maintain global application state.
To me it sounds like the strings are just part of the application state. Create a subclass of Application, register that class in AndroidManifest.xml as your application class and store the strings there. Then you can access the strings from all of your activity classes by calling getApplication()...
Upvotes: 1