I am trying to get my fragment working and I cant get it done whatever I am trying to do.
The error I am getting is:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
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);
}
}
Have no idea why it doesn't work. I am testing this class just to see if the text will be changed on the textview. I am using the right id because I checked that like 10 times, yet I think the problem is because textview one is a null object. But why it doesn't find the id?
onCreate()
is called before onCreateView()
and therefore you will not be able to access it in onCreate()
.
Solution: Move
one = (TextView) getActivity().findViewById(R.id.one);
to onViewCreated()
instead.
See picture below for an overview of the fragment lifecycle.
The new snippet looks like this:
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");
}
}
Or. instead of rewriting
public void onViewCreated(View view, Bundle savedInstanceState)
you can slightly change your onCreateView so it looks like
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With