-1
public class Device extends Fragment {
TextView textv;

    public Device() {

        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        textv = this.getView().findViewById(R.id.tv1);
        textv.setText(Build.PRODUCT);


        return inflater.inflate(R.layout.fragment_device, container, false);

    }


}

This gives me this error:

Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference

letsintegreat
  • 3,328
  • 4
  • 18
  • 39
  • Try doing getActivity().findViewById() instead of this.getView().findViewById() – Karan Mehta Feb 11 '20 at 06:04
  • Hi welcome!, please check here, does this answer your question https://stackoverflow.com/questions/6495898/findviewbyid-in-fragment?page=1&tab=votes#tab-top – Ashwini Saini Feb 11 '20 at 06:15

3 Answers3

1

Try below solution

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_device, container, false);
    textv = view.findViewById(R.id.tv1);
    textv.setText(Build.PRODUCT);
    return view;
}

I hope this can help you!

Thank you!

Hardik Talaviya
  • 1,396
  • 5
  • 18
  • E:\Android_Project\Whatsapp\app\build\intermediates\signing_config\debug\out\signing-config.json (Access is denied) – Abdur Rehman Feb 11 '20 at 06:11
0

try below by overriding onViewCreated

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        textv = view.findViewById(R.id.tv1);
        textv.setText(Build.PRODUCT);

    }
Maulik Togadiya
  • 594
  • 5
  • 10
0

You can do like this in your fragment onCreateView() method

 View rootView;
 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {
      rootView= inflater.inflate(R.layout.fragment_device, container, false);   
      initViews();
      return rootView;
 }

public void initViews(){
      textv = rootView.findViewById(R.id.tv1);
      textv.setText(Build.PRODUCT);
}
PlusInfosys
  • 3,416
  • 1
  • 19
  • 33