简体   繁体   中英

java.lang.NullPointerException at java.util.Objects.requireNonNull

In my code, I am calling aa function addFood as follows from an activity

postFood f = new postFood();
f.addFood(context, breakfastDate, breakfastSearch, 1);

and then the code runs the following code

public class postFood extends DialogFragment {
    @SuppressLint("StaticFieldLeak")
    private static Context context1;
    @SuppressLint("StaticFieldLeak")
    private static ListView dateList1, selectedList1;
    private static ProgressDialog progressDialog;
    private static int mealType1;
    private static String TAG = "AddSelectedFood";
    private static String date;
    private static String time;
    public static String[] dateTimeString;
    public static Calendar cal;


    public  void addFood(Context context, ListView dateList, ListView selectedList,
                           int mealType) {
        dateList1 = dateList;
        selectedList1 = selectedList;
        context1 = context;
        mealType1 = mealType;
        //*FragmentManager manager = Objects.requireNonNull(this.getActivity()).getSupportFragmentManager();

        // Use the current date as the default date in the picker
        new datePickerFragment().show(Objects.requireNonNull(getActivity()).getSupportFragmentManager(), "datePicker");
    }
}

What can I do in order to prevent getActivity().getSuppotFragmentManaget from being null?

here is my LOG

2019-01-15 12:08:37.898 7908-7908/com.example.khali.nutriplan E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.khali.nutriplan, PID: 7908
java.lang.NullPointerException
    at java.util.Objects.requireNonNull(Objects.java:203)
    at com.example.khali.nutriplan.postFood.addFood(postFood.java:63)
    at com.example.khali.nutriplan.breakfastPage$1.onClick(breakfastPage.java:114)
    at android.view.View.performClick(View.java:6597)
    at android.view.View.performClickInternal(View.java:6574)
    at android.view.View.access$3100(View.java:778)
    at android.view.View$PerformClick.run(View.java:25885)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

Ok let me explain it really quick. What vaibhav kumar mentioned in his comment is correct, but I think you did not fully understand it yet. The idea is to pass the Context from the calling Activity to the Fragment. Why? Think of Fragments as small UI-Elements that you can dynamically make use of inside of an Activity. Here we come to the first important thing: Make sure the Activity which contains your Fragment is not just an Activity, but a FragmentActivity . Now, you can do two things:

  1. getFragmentManager() : Return the FragmentManager for interacting with fragments associated with this fragment's activity. Note that this will be non-null slightly before getActivity(), during the time from when the fragment is placed in a FragmentTransaction until it is committed and attached to its activity. This is not an option for you because obviously, your Fragment is not yet used by any Activity.
  2. Use the Context you passed to your Fragment. It contains information about the currently active Activity. Remember that your Fragment is still not attached to it though. So what you do is: context.getActivity(). getSupportFragmentManager()

This should solve your issues. Always keep the different states of a Fragment in mind and how they affect its behavior. Your Fragment for example is not even attaching yet.

It is a bit hard to tell why getActivity() is null since we don't know where you are calling your method.

You must know that getActivity() is null before onAttach() and after onDestroy() , if you call your method between these two methods you should be good.

What can I do in order to prevent getActivity().getSuppotFragmentManaget from being null?

Brutally answering your question. When you use getActivity() in your code it is a good practice to cast it to make sure it is not null (unless you are sure it is not null). In your code, it would be like that.

    // Use the current date as the default date in the picker
    if (getActivity != null){
        new datePickerFragment().show(Objects.requireNonNull(
            getActivity()).getSupportFragmentManager(), "datePicker");
    }

By using these you will not have the problem getActivity.getSupportFragmentManager() being null. BUTT , this is because this part of your code will not run anymore. It will see getActivity() is null and it will not follow the code.

From now, your app will not crash anymore, however, you will not see the Dialog. Now you need to prevent getActivity() from being null. For that I recommend you to.

  1. Check where you are calling your method;
  2. Try to call your method from different places;
  3. Make sure your activity/fragment is inside onAttach() and onDestroy() method when you use getActivity() .

You are instantiating the fragment but you are not adding it to the UI. Since the fragment is not attached to the activity when you call the addFood method, getActivity() returns null.

postFood f = new postFood();
f.addFood(context, breakfastDate, breakfastSearch, 1);

After instantiating you should call the show method to add the fragment instance to the UI

postFood f = postFood.newInstance(context, breakfastDate, breakfastSearch, 1);
f.show(getSupportFragmentManager(), "MyTAG");

and call the addFood method inside the onViewCreated method from your fragment

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState){
    super.onViewCreated(view, savedInstanceState);
    addFood(); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM