Reputation: 41
I am getting the following error message:
"Cannot make a static reference to the non-static method getPreferences(int) from the type Activity" is the error in my case. 'TimeCardLogin' must be a static variable."
How do I get a preference into a static String
variable?
public class MyBaseURLContainer extends Activity {
public static String urlPref = "";
static String BASE_URL =
getPreferences(MODE_PRIVATE).getString("Name of variable",urlPref);
public static final String TimeCardLogin = BASE_URL + "/timecard";
}
Upvotes: 0
Views: 553
Reputation: 2411
I'd recommend making a static getter that takes an Context as an argument. That way a) it will actually compile, and b) if your base-url changes at some point, it will load the most recent value, instead of loading once in the beginning like your program is:
private final static String PREFS = "myUrlPrefs";
public static String getBaseUrl(Context context) {
return context.getSharedPreferences(PREFS, MODE_PRIVATE).getString(
"Name of variable",urlPref);
}
You'd call it from another activity like this:
String baseUrl = MyBaseUrlContainer.getBaseUrl(this);
Or from anywhere you have access to a Context like this (an Activity is a Context):
String baseUrl = MyBaseUrlContainer.getBaseUrl(myContext);
If you absolutely have to use this code from somewhere that doesn't have access to a Context (which really should almost never be the case in an Android app), you could store the value after it's retrieved, but the first time you get the value it has to be from a Context.
Upvotes: 2