0

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?

Martin Seal
  • 616
  • 2
  • 14
  • 32
  • did you check that findViewById() actually found the switch, ie are you sure switchCompat is not null? – nPn May 22 '16 at 21:39
  • No, its just in the same layout, I can play with the switch if I don't call the set change listener how would I do that just literally if(mySwitch != Null) @nPn – Martin Seal May 22 '16 at 21:56

1 Answers1

0

Your mistakes is:

getActivity()

Change to:

switchCompat = (SwitchCompat) rootView.findViewById(R.id.mySwitch);
Lucas
  • 431
  • 3
  • 7
  • The item "mySwitch" is inside rootView, do not Activity! :D bye bye NullPointerException – Lucas May 22 '16 at 22:13