This question has already been answered:

Good day.

Error java.lang.NullPointerException

Error on the line with the assignment.
If it has not yet been created, that is, default, why is NullPointerException ?

 SharedPreferences settings; SharedPreferences.Editor editor; boolean ifWasSet; public void makeList() { ifWasSet = settings.getBoolean("comp", false); if (ifWasSet == true) { System.out.println("Ne dobavlyaem"); } else { persons.add(student1); persons.add(student2); persons.add(student3); persons.add(student4); settings = getApplicationContext().getSharedPreferences(STORAGE_NAME, Context.MODE_PRIVATE); editor = settings.edit(); editor.putBoolean("comp", true); editor.commit(); } } 

Reported as a duplicate by Vladyslav Matviienko android 30 Sep '16 at 12:21

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • you have the settings variable used before if , and you assign a value to it only in the else block. That is how it should be? - Nikotin N
  • The fact is that I have data that I need to add only once. First, everything should be FALSE, and then after one addition it is always TRUE. - T.Tester

1 answer 1

you try to use settings before you write something to it. ifWasSet = settings.getBoolean("comp",false); First write something in settings , and then call its methods.

  • The fact is that I can’t assign a value to it first, because after the re-creation of the activation, the value changes from TRUE to FALSE. - T.Tester
  • 2
    @ T.Tester, but I will. Before you say, "car, drive!" need to buy a car. If you say “ed” to an empty place, then nothing good will happen. - Vladyslav Matviienko September