我收到以下错误消息:
"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."
如何获取静态 String
变量的首选项?
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";
}
最佳答案
我建议创建一个以 Context 作为参数的静态 getter。这样a)它实际上会编译,b)如果你的base-url在某个时候发生变化,它将加载最新的值,而不是像你的程序那样在开始时加载一次:
private final static String PREFS = "myUrlPrefs";
public static String getBaseUrl(Context context) {
return context.getSharedPreferences(PREFS, MODE_PRIVATE).getString(
"Name of variable",urlPref);
}
您可以从另一个 Activity 中调用它,如下所示:
String baseUrl = MyBaseUrlContainer.getBaseUrl(this);
或者从任何可以访问上下文的地方,如下所示( Activity 就是上下文):
String baseUrl = MyBaseUrlContainer.getBaseUrl(myContext);
如果您绝对必须在无法访问上下文的地方使用此代码(在 Android 应用程序中几乎不应该出现这种情况),您可以在检索该值后存储该值,但第一次您可以从上下文中获取它必须具有的值。
关于java - 如何将首选项值获取到静态字符串变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16000291/