【发布时间】: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