Android and reference to the null object

I am trying to make my fragment work, and I cannot do everything that I am trying to do.

The error I am getting is:

java.lang.NullPointerException: attempt to call the virtual method void android.widget.TextView.setText (java.lang.CharSequence) 'to reference the null object

Here is the code:

public class FragmentOne extends Fragment {

    private TextView one;

    public FragmentOne() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        one = (TextView) getActivity().findViewById(R.id.one);

        // Displaying the user details on the screen
        one.setText("kjhbguhjg");

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment1, container, false);

    }
}

I don’t know why this is not working. I am testing this class only to see if the text will be changed in text form. I use the correct identifier because I checked it like 10 times, but I think the problem is that textview one is a null object. But why doesn't he find the identifier?

+4
source share
2 answers

onCreate() onCreateView(), onCreate().

:

one = (TextView) getActivity().findViewById(R.id.one);

onViewCreated().

. .

:

public class FragmentOne extends Fragment {


    private TextView one;

    public FragmentOne() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment1, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState){
        one = (TextView) getActivity().findViewById(R.id.one);
        // Displaying the user details on the screen
        one.setText("kjhbguhjg");
    }
}

Fragment life cycle

+8

.

public void onViewCreated(View view, Bundle savedInstanceState)

onCreateView,

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment1, container, false)
one = (TextView) rootView.findViewById(R.id.one)
return rootView;
}
+2

Source: https://habr.com/ru/post/1614078/


All Articles