【问题标题】:Android getSharedPreferences in static block of a class类的静态块中的Android getSharedPreferences
【发布时间】:2012-06-20 07:22:00
【问题描述】:

在我的应用程序中,我需要根据用户存储在 SharedPreference 变量中的值声明一个数组。问题是数组需要在静态块中声明,因为数组的大小需要在我的类中调用 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);
    }

}

如果我没有在静态块中声明数组,那么我会收到一个错误

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

有什么方法可以实现吗?

【问题讨论】:

    标签: java android static sharedpreferences


    【解决方案1】:

    不,你不能。自从

    static {
    }
    

    当您第一次引用该类时会调用块。所以,我认为,在onCreate si 调用之前。要访问SharedPreference,您需要一个context,并且contextonCreate 之后有效。所以你不能在静态块中访问SharedPreference

    【讨论】:

    • 我编辑了我的问题。如果可能,请检查并提出任何建议。
    • 您在哪里尝试检索 sharedPreference?
    • 我想在静态块里面做。但是,它给出了错误。我的问题中给出的代码正在运行,但我也想将 SharedPreferences 包括在内。
    • 你不能。 1. 因为你需要的 Context 实例不存在 2. 你正在调用 getSharedPreferences(),但当然是 this.getSharedPreferences() (对当前活动实例的引用),并且由于 this 不能是静态的,所以你不能访问到共享首选项
    • 那么如何创建一个数组,其大小存储在手机内存中?
    【解决方案2】:

    首先,我不得不说你的方法听起来有点奇怪。为什么要将数组声明为静态并在 onCreate 之前对其进行初始化?如果这确实是一个要求,那么我不确定是否有解决方案,因为 onCreate() 是您第一次访问上下文。

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

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

    【讨论】:

    • 我编辑了我的问题。如果可能,请检查并提出任何建议。
    猜你喜欢
    • 2015-06-07
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    • 2015-10-04
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多