2

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();
}
  • 3
    Put a break point on this line: `Toast.makeText(mainActivity, "" + tof, Toast.LENGTH_SHORT).show();`, then inspect the `mainActivity` to make sure it is not null. – CzarMatt Jul 26 '17 at 23:08
  • @Karolis Kursevičius This is not the issue but you don't need to do `getContext().getApplicationContext()` to get the Context. Just call `getContext()` it'll be fine. – Eselfar Jul 27 '17 at 10:44
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Henry Jul 28 '17 at 11:29

3 Answers3

0

Try to change: editor.putBoolean("isDoingChallenge", false).apply();

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

Iulian Popescu
  • 2,595
  • 4
  • 23
  • 31
João Armando
  • 167
  • 2
  • 12
0

The problem is with your mainActivity variable - it's null.

The logcat shows that you are trying to create a Toast that is not able to getResources() (because the context is null).

If you call getActivity() instead of using mainActivity - it should fix the crash.

jt-gilkeson
  • 2,661
  • 1
  • 30
  • 40
  • Thank you very much. This helped with one problem. But maybe you know how an I get mainActivity not to be null. Because I have an method there that I want to use in my fragments. –  Jul 27 '17 at 17:20
  • If you want to set a variable for the mainActivity - should should do it in your Fragment's onCreateView method (mainActivity = getActivity()). Although my preference is to always just call getActivity() instead of keeping a variable. – jt-gilkeson Jul 27 '17 at 18:06
0

You are passing getContext().getApplicationContext() to PreferencesHelper constructor and calling context.getApplicationContext() again from the constructor.

Try changing the PreferencesHelper constructor as follows.

public PreferencesHelper(Context context) {
    this.sharedPreferences = context.getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
    this.editor = sharedPreferences.edit();
}
taug
  • 378
  • 1
  • 8
  • i used a variable of an activity where the fragment is (MainActivity) to use a method in it. But later I changed it to ((MainActivity) getActivity()).methodName.. and it worked –  Jul 28 '17 at 10:55