0

I opened dialog in a fragment and when come back to fragment, my fragment's view is null Object.
when the dialog is displaying which lifecycle method fragment is calling?

public class MyFragment extends Fragment{
  TextView textView;
  View view;
  FloatingActionButton actionButton;

  @Override
  public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragment_read, container, false); 

    textView = view.findViewById(R.id.txtSaved);
    actionButton = view.findViewById(R.id.floatingActionButton);

    actionButton.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        DialogSearch search = new DialogSearch();
        search.show(getActivity().getSupportFragmentManager(),"MyDialog");
      }
    });
   return view;
  }
}
Amir2511
  • 37
  • 7

2 Answers2

0

Make a small change,

 public class MyFragment extends Fragment{
        TextView textView;
        View view;
        FloatingActionButton actionButton;

        @Override
        public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            view = inflater.inflate(R.layout.fragment_read, container, false); 

            textView = view.findViewById(R.id.txtSaved);
            actionButton = view.findViewById(R.id.floatingActionButton);

            actionButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    DialogSearch search = new DialogSearch();
                    search.show(getActivity().getSupportFragmentManager(),"MyDialog");
                }
            });
    return view;   / Add this line -------   
     }
    }

You need to return view

when the dialog is displaying which lifecycle method fragment is calling?

onPause() of fragment gets called.
Chethan Shetty
  • 179
  • 1
  • 10
0

The problem is the dialog is being showned in the onCreateView life cycle, that is why is the Fragment view is null. You have to do it inside the onViewCreated method.

    @Override
    public View onViewCreated(View view, Bundle savedInstanceState) {
       //Work here, the view argument in the method is the view inflated in the onCreateView method
    });
cutiko
  • 9,887
  • 3
  • 45
  • 59