0

Null Pointer Exception occurs at times randomly. Occurs mostly when pressed the backpressed from a particular fragment.

Exception occurs when tries to pass a param called "userregid" using Volley.

 params.put("userregid", Utils.getString(((BaseActivity)getActivity()).get_hospital_userreg_id()));

I wrote a method in a BaseActivity to identify the hospital_userreg_id according to the conditions. This is the function ,

 public int  get_hospital_userreg_id() {

    int userreg_id = 0;

    switch (AppConst.HOSPITAL_CURRENT_ID) {

        case 36:
            userreg_id = AppConst.HOSP_ONE_USERREG_ID;
            break;
        case 37:
            userreg_id = AppConst.HOSP_TWO_USERREG_ID;
            break;
    }

    return userreg_id;
}

I feel that the issue is related to calling the function from the fragment. Any solutions ?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Clint Paul
  • 313
  • 2
  • 6
  • 18
  • 1
    This code needs Debugging nothing else. Try to find out which object is null on `onbackPressed()`. – ADM Dec 27 '17 at 10:00
  • hey you are passing integer to string that is wrong otherwise typecast it... – Dilip Dec 27 '17 at 10:00
  • @Dilip I'm using Utils.getString to typeCast it to String. It's working perfectly in most conditions. but at some point it show's null pointer exception. 'public static String getString(int number) { return String.valueOf(number); }' – Clint Paul Dec 27 '17 at 10:02
  • hard to say without stacktrace, but `getActivity()` probably returns `null` because your fragment is already gone away from the activity – JohnnyAW Dec 27 '17 at 10:04
  • hey @Clint Paul please check null before put in params like if(null!= Utils.getString(((BaseActivity)getActivity()).get_hospital_userreg_id())){params.put("userregid", Utils.getString(((BaseActivity)getActivity()).get_hospital_userreg_id())); } – Dilip Dec 27 '17 at 10:04
  • @JohnnyAW So, should I call like ((BaseActivity)getContext) instead of ((BaseActivity)getActivity) ? – Clint Paul Dec 27 '17 at 10:07
  • @Dilip Is it a practical solution ? coz then I have to put null pointer check in every network call – Clint Paul Dec 27 '17 at 10:08
  • I don't know, depends on what you need. I think `getContext` would also return `null` in this case – JohnnyAW Dec 27 '17 at 10:08
  • @JohnnyAW , Yes tried with getContext too. getting nullpointer at some stage. So , is it better if I write the method from some other class instead from a BaseActivity ? – Clint Paul Dec 27 '17 at 10:11
  • you could try to use another hook, like `onDetach` so you know, that after this your fragment is not longer available on the activity – JohnnyAW Dec 27 '17 at 10:12
  • @JohnnyAW okay I'll try both ways and will update once the issue is solved. Thanks for your time – Clint Paul Dec 27 '17 at 10:15

0 Answers0