-1

I have a fragment in MainActivity and try to setText in fragment, but when I try to do it I get Null Pointer Exception. I checked spelling but it seems okay. I debug app and check these variables but it doesnt seem they are null.

The exception appear in first line of clearText() method.

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.fragment_sun, container, false);

        sunRiseTime = v.findViewById(R.id.sunRiseTime);
        sunRiseAzimuth = v.findViewById(R.id.sunRiseAzimuth);
        sunSetTime = v.findViewById(R.id.sunSetTime);
        sunSetAzimuth = v.findViewById(R.id.sunSetAzimuth);
        duskTime = v.findViewById(R.id.duskTime);
        dawnTime = v.findViewById(R.id.dawnTime);

        return v;
    }

private void clearText(){
        sunSetTime.setText("");
        sunSetAzimuth.setText("");
        sunRiseTime.setText("");
        sunRiseAzimuth.setText("");
        duskTime.setText("");
        dawnTime.setText("");
    }

The error

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
                                                       at com.example.mariusz.astroweather.SunFragment.clearText(SunFragment.java:99)
denvercoder9
  • 2,979
  • 3
  • 28
  • 41

1 Answers1

0

Check and trace inside your onCreateView() and see if sunSetTime TextView is not Null. It might happen that you have alternate layouts for R.layout.fragment_sun which might does not include sunSetTime TextView. If this is not the case, it might happen that you call clearText() before onCreateView.

VSB
  • 9,825
  • 16
  • 72
  • 145