Prashanth T P
Prashanth T P

Reputation: 136

Accessing TextView inside a fragment is giving NullPointerException

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.

Upvotes: 3

Views: 47

Answers (1)

Reaz Murshed
Reaz Murshed

Reputation: 24211

You are getting an NPE because the view of the Fragment was not yet loaded when you are trying to set the text using the setContentOfTextView function from your activity.

The views in your fragment needs to be inflated first, in order to load something in it. Hence, you should do this in your fragment's onCreateView function.

About passing the information from your activity - you can easily do that using a Bundle passed to your fragment while launching it from your activity.

Here's how you can do that.

In your activity, pass the data using a Bundle while launching your fragment.

@Override
public void fragmentRespond(int index) {

    // Prepare the bundle
    Bundle bundle = new Bundle();
    bundle.putInt("index", index);

    FragmentTransaction transaction =  fragmentManager.beginTransaction();
    Fragment2 fragment2 = new Fragment2();
    fragment2.setArguments(bundle); // Set the arguments here to be passed on to your fragment while loading.

    transaction.add(R.id.group2,fragment2, "fragment2");
    transaction.commit();
    transaction.addToBackStack("fragment2");
}

And in your fragment, get the desired data from that Bundle and load it into your TextView.

@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);

    // Load the information in your TextView here
    Bundle args = getArguments();
    if (args != null && args.containsKey("index")) {
        setContentOfTextView(args.getInt("index"));
    }

    Toast.makeText(getContext(),"OnCreateView",Toast.LENGTH_LONG).show();
    return  view;
}

I hope that helps.

Upvotes: 2

Related Questions