我正在使用TabLayout,並且我有3個片段。當我嘗試從SharedPreferences獲取值時,第一個Fragment中出現NullPointerException。 Context對象有什麼問題嗎?請幫忙。感謝 logcat的:在片段中使用SharedPreferences時獲取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',以確保它不爲空。 – CzarMatt
@KarolisKursevičius這不是問題,但您不需要執行'getContext()。getApplicationContext()'來獲取上下文。只要調用'getContext()'就可以了。 – Eselfar
可能的重複[什麼是NullPointerException,以及如何解決它?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it ) – Henry