java - 类的静态 block 中的Android getSharedPreferences

标签 java android static sharedpreferences

在我的应用程序中,我需要根据用户存储在 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,并且 contextonCreate 之后有效。所以你不能访问静态 block 中的SharedPreference

关于java - 类的静态 block 中的Android getSharedPreferences,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11114684/

相关文章:

android - 使用 Android 从摄像机捕获 WiFi 信号

javascript - 路由到静态 HTML 页面,以及 Express 中的模板化动态路由

c++ - 在构造函数中创建线程

Android:strings.xml 中的文本显示为@numbers

使用 getter 和 setter 存储全局 std::string 标签的 C++ 策略

java - 在 IntelliJ 的 Java 项目中使用 .gdsl 文件

java - 在 Java 中使用 Comparator 时无法编译的源代码

java - 供个人使用的持续集成

java - Pitest 无法检测测试类别

尝试使用 pdfrenderer 将 pdf 页面解析为图像时出现 java.lang.NoClassDefFoundError : java. awt.geom.Rectangle2D$Double