【问题标题】:Getting NullPointerException when using SharedPreferences in Fragment在 Fragment 中使用 SharedPreferences 时出现 NullPointerException
【发布时间】:2017-07-26 22:49:01
【问题描述】:

我正在使用 TabLayout,我有 3 个片段。当我尝试从 SharedPreferences 获取值时,我在第一个 Fragment 中得到 NullPointerException。上下文对象有问题吗?请帮忙。谢谢 日志猫:

java.lang.NullPointerException: Attempt to invoke virtual method 
'android.content.res.Resources android.content.Context.getResources()' on a 
null object reference
/me.karolis.notsecretproject W/System.err: at android.widget.Toast.<init>
(Toast.java:102)
/me.karolis.notsecretproject W/System.err: at 
android.widget.Toast.makeText(Toast.java:260)
/me.karolis.notsecretproject W/System.err:     at 
me.karolis.notsecretproject.fragments.MainFragment$1.onItemClick 
(MainFragment.java:63)me.karolis.notsecretproject.fragments. 
MainFragment$1.onItemClick(MainFragment.java:63)

我的偏好助手类:

public class PreferencesHelper {

private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;

public PreferencesHelper(Context context) {
    this.sharedPreferences = context.getApplicationContext().getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
    this.editor = sharedPreferences.edit();
}

public boolean getIsDoingChallenge() {
    return sharedPreferences.getBoolean("isDoingChallenge", false);
}

public void setIsDoingChallenge(boolean tof) {
    editor.putBoolean("isDoingChallenge", tof).apply();
}

}

第一个片段(问题所在):

public class MainFragment extends android.support.v4.app.Fragment {

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_main, container, false);

    listView = (ListView) view.findViewById(R.id.fragment_main_list_view);

    listView.setAdapter(adapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            try {
                DatabaseHandler db = new DatabaseHandler(getContext().getApplicationContext());
                PreferencesHelper preferenceHelper = new PreferencesHelper(getContext().getApplicationContext());
                boolean tof = preferenceHelper.getIsDoingChallenge();
                Toast.makeText(mainActivity, "" + tof, Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    return view;
}

数据库(这是我创建 SharedPreferences 的地方):

public class DatabaseHandler extends SQLiteOpenHelper {

@Override
public void onCreate(SQLiteDatabase database) {
    SharedPreferences sharedPreferences = context.getApplicationContext().getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean("isDoingChallenge", false).apply();
}

【问题讨论】:

  • 在这一行放一个断点:Toast.makeText(mainActivity, "" + tof, Toast.LENGTH_SHORT).show();,然后检查mainActivity以确保它不为空。
  • @Karolis Kursevičius 这不是问题,但您无需执行getContext().getApplicationContext() 即可获取上下文。只需拨打getContext() 就可以了。

标签: android android-fragments nullpointerexception sharedpreferences


【解决方案1】:

问题在于您的 mainActivity 变量 - 它为空。

logcat 显示您正在尝试创建一个无法创建 getResources()Toast(因为上下文为空)。

如果您调用getActivity() 而不是使用mainActivity - 它应该可以修复崩溃。

【讨论】:

  • 非常感谢。这有助于解决一个问题。但也许你知道我如何让 mainActivity 不为空。因为我有一个方法想在我的片段中使用。
  • 如果你想为 mainActivity 设置一个变量 - 应该在你的 Fragment 的 onCreateView 方法 (mainActivity = getActivity()) 中进行。虽然我的偏好是始终只调用 getActivity() 而不是保留变量。
【解决方案2】:

您将getContext().getApplicationContext() 传递给PreferencesHelper 构造函数,并从构造函数再次调用context.getApplicationContext()

尝试如下更改PreferencesHelper 构造函数。

public PreferencesHelper(Context context) {
    this.sharedPreferences = context.getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
    this.editor = sharedPreferences.edit();
}

【讨论】:

  • 我使用了片段为 (MainActivity) 的活动的变量来使用其中的方法。但后来我把它改成了 ((MainActivity) getActivity()).methodName.. 它工作了
【解决方案3】:

尝试更改:editor.putBoolean("isDoingChallenge", false).apply();

与:editor.putBoolean("isDoingChallenge", false).commit();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-20
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多