A fragment is defined as follows. I am trying to set Text of positionTextView.
public class Fragment2 extends Fragment {
private TextView positionTextView,fragment2TextView;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout_fragment2, container, false);
positionTextView = view.findViewById(R.id.positionTextView);
fragment2TextView = view.findViewById(R.id.fragment2TextView);
Toast.makeText(getContext(),"OnCreateView",Toast.LENGTH_LONG).show();
return view;
}
public void setContentOfTextView( int position) {
positionTextView.setText(Integer.toString(position));
}
}
And in the MainActivity, I am adding the Fragment2 as follows.
@Override
public void fragmentRespond(int index) {
FragmentTransaction transaction = fragmentManager.beginTransaction();
Fragment2 fragment2 = new Fragment2();
transaction.add(R.id.group2,fragment2,"fragment2");
transaction.commit();
transaction.addToBackStack("fragment2");
fragment2.setContentOfTextView(index);
}
I have the fragmentRespond function in another fragment which contains a ListView. The ListView's onItemClickListener calls this function, i.e, fragmentRespond(int index).
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String[] quotes = getResources().getStringArray(R.array.quotes);
CustomArrayAdapter customArrayAdapter = new CustomArrayAdapter(getContext(),quotes,null);
listView.setAdapter(customArrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
fragmentCommunicator.fragmentRespond(position);
}
});
}
And I am getting the following error
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
Any suggestions regarding this problem or improving the coding style is very well appreciated.
Thank you in advance.