Android 9.0 设备上的 NumberFormatException,无法找到问题的原因

NumberFormatException on Android 9.0 devices, unable to find cause of issue

对于在 Android 9.0 上仅使用 Pixel/Pixel 2 部手机的用户,我的部分代码崩溃了。我已经使用 Android 模拟器测试了尽可能多的情况,但无法重现报告的 NumberFormatException.

这里是崩溃所指的代码:

public void onRecieve(...) {
     //...
     int network_pref = Integer.parseInt(getDefaults("network_pref", context));
     //...
}

public static String getDefaults(String key, Context context) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getString(key, null);
    }

首选项的默认值为“0”,唯一的其他选项为“1”。

您可能会得到默认方法返回 null,因为这是您传递的值。

你可以试试这个,它可能会奏效...

public static String getDefaults(String key, Context context) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    return preferences.getString(key, "0");
}