Martin Seal Martin Seal - 6 months ago 68
Android Question

why is Switch Compat causing null pointer in fragment when calling onCheckedChange

rather explanatory title
here is the xml

<android.support.v7.widget.SwitchCompat
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/mySwitch"
app:showText="false"
android:textOn="On"
android:textOff="Off"
android:layout_marginLeft="@dimen/activity_horizontal_margin"
android:layout_marginRight="@dimen/activity_horizontal_margin" />


and here is the main of what im doing in my fragment

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.intro_frag, container, false);
getPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
switchCompat = (SwitchCompat) getActivity().findViewById(R.id.mySwitch);

return rootView;

}

@Override
public void onActivityCreated(final Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
switchCompat.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean
isChecked) {
if (isChecked) {
//do stuff
}
else if (!isChecked){
//do other stuff
}
}
});


the line switchCompat.setOnCheckedChangeListener is causing a null pointer exception without it everything runs fine ive searched the issue and found a few fixes like the switch needing text and stuff but i cannot get this working can anybody help?

Answer

Your mistakes is:

getActivity()

Change to:

switchCompat = (SwitchCompat) rootView.findViewById(R.id.mySwitch);