I want to change texts in fragments, but I keep getting error like this
java.lang.NullPointerException: Attempt to read from field 'android.widget.TextView com.javahelp.databinding.FragmentHomeBinding.Aboutus' on a null object reference in method 'android.view.View com.javahelp.frontend.fragments.HomeFragment.onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)'
`
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_home, container, false);
binding.Aboutus.setText("Changed");
return v;
}
`
The one below is the mainpage where I am switching fragments `
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityFgBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
replaceFragment(new HomeFragment());
binding.bottomNavigationView.setOnItemSelectedListener(item ->{
switch(item.getItemId()){
case R.id.home:
replaceFragment(new HomeFragment());
break;
case R.id.account:
replaceFragment(new AccountFragment());
break;
case R.id.search:
replaceFragment(new SearchFragment());
break;
}
return true;
});
}
`
I was expecting the word "About Us" in home fragment would change to "Changed". I am trying to see if setText is working, but it is not. I looked for possible solutions, but they are not working.So I am not sure how to solve this. Appreciate some help and suggestions!
you can not set text in onCreateView method, put this line into onViewCreated method