I'm using TabLayout and I have 3 fragments. I get a NullPointerException in the first Fragment when I try to get a value from SharedPreferences. Is there a problem with the Context object or something? Please help. Thanks Logcat:
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)
My Preference Helper Class:
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();
}
}
The first fragment (where the problem is):
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;
}
Database (this is where I create my 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();
}