Android中的getSharedPreferences类的静态块

时间:2012-06-20 07:22:00

标签: java android static sharedpreferences

在我的应用程序中,我需要根据用户在SharedPreference变量中存储的值声明一个Array。问题是数组需要在静态块中声明,因为在我的类中调用onCreate()之前需要声明数组的大小。

我的Activity中有一个ExpandableList,父数组作为接下来七天的日期。

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);
    }

}

如果我没有在静态块中声明数组,那么我在

处收到错误
public View getGroupView(int groupPosition, boolean isExpanded,
            View convertView, ViewGroup parent) {
        TextView textView = getGenericView();
        textView.setText(getGroup(groupPosition).toString());
        return textView;
    }

所以,我想我必须在静态块中声明数组的内容。

问题是我想要更改显示的天数(目前设置为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

有没有办法实现这个目标?

2 个答案:

答案 0 :(得分:1)

不,你不能。

static {
}
第一次引用类时会调用

块。所以,我认为,在调用onCreate之前。要访问SharedPreference,您需要context,而contextonCreate之后有效。因此,您无法访问静态块中的SharedPreference

答案 1 :(得分:0)

首先,我必须说你接近声音有点奇怪。为什么要将数组声明为静态并在onCreate之前初始化它?如果这确实是一个要求,那么我不确定是否有解决方案,因为onCreate()是您第一次访问上下文。

我可以建议您将数组定义为静态,然后在onCreate中初始化它(在使用它之前)。除非在您的活动之外使用该数组,否则这应该有效。

也许如果您分享了更多详细信息(例如为什么它必须是静态的并且在onCreate之前启动),您可以获得更多帮助。