在我的应用程序中,我需要根据用户存储在 SharedPreference 变量中的值声明一个数组。问题是数组需要在静态 block 中声明,因为在我的类中调用 onCreate() 之前需要声明数组的大小。
我的 Activity 中有一个 ExpandableList,父数组作为接下来 7 天的日期。
static int plannerSlotCount=7;
static public String[] parent = new String[plannerSlotCount];
static
{
Calendar cal = Calendar.getInstance();
String strdate = null;
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
int i;
for(i=0;i<plannerSlotCount;i++)
{
if (cal != null) {
strdate = sdf.format(cal.getTime());
}
parent[i] = strdate;
cal.add(Calendar.HOUR_OF_DAY,24);
}
}
如果我不在静态 block 中声明数组,那么我会在
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
TextView textView = getGenericView();
textView.setText(getGroup(groupPosition).toString());
return textView;
}
所以,我想我必须在静态 block 本身中声明数组的内容。
问题是我想更改要显示的天数(目前设置为 7)。因此,我考虑将数字保存在 SharedPreference 变量中并访问它以初始化数组。
我遇到的问题是
SharedPreferences preferences = getSharedPreferences(Settings.PREF_SETTINGS_FILE_NAME, MODE_PRIVATE);
final int slotCounter = preferences.getInt("slotCount", 7);
给我一个错误说
Cannot make a static reference to the non-static method getSharedPreferences(String, int) from the type ContextWrapper
有什么办法可以实现吗?
最佳答案
不,你不能。由于
static {
}
block 在您第一次引用该类时被调用。所以,我认为,在调用 onCreate
之前。为了访问 SharedPreference
,您需要一个 context
,并且 context
在 onCreate
之后有效。所以你不能访问静态 block 中的SharedPreference
关于java - 类的静态 block 中的Android getSharedPreferences,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11114684/