Hi Jacob. Thanks for publishing this series of tutorials but there is something regarding this that…


I do not exactly understand what you’re trying to do, but I’ve found this:

In your FragmentBlueShapes you inflate fragment_blueshapes.xml as your rootView . After this you try to find a view with the id R.id.square_switch within this view, which does not exists there. That’s why you get the NullPointerException when you try to do anything with the not existing Switch.

The Switch with the id seems to be in your activity_settings.xml which is used in the SettingsActivity and not in your Fragment.

This is what you should do:

In your SettingsActivity you should search for your switch, detect changes and save its state to the preferences (as you do at the moment).

In your BlueShapesActivity you should add your fragment, as you do at the moment.

But in your FragmentBlueShapes you have to change some things:
1. In onCreateView : Since you don’t have a Switch in your fragment_blueshapes.xml , remove the lines where you search for it and the lines where you try to set a listener to it. (You can directly return the inflated rootView .
2. In loadPreferences : You load the value from the preferences and save it in the global variable diagramState . That should be okay.
3. In displaySettings : You can search for your views contained in the fragment_blueshapes.xml (R.id.blue_square , R.id.blue_circle and R.id.blue_rectangle ) and toggle their visibility depending on the global variable diagramState.

I really don’t understand why you try to find the switch again in your fragment, that has nothing to do with the settings activity.

Hope this helps.

Like what you read? Give Jakob Ulbrich a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.