Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerException when accessing a Fragment's textView in an Activity

It seems to be a common problem, but after hours of trying random solutions provided as answers to similar questions, my code still produces a NullPointerException when I access a Fragment's textView from an Activity.

I can include (and view) my Fragment when its textView has a predefined Text or by using setText() in onCreateView() of the Fragment class but not by using a setter method (here set_message_success()).

This is my Fragment class Fragment_Message:

public class Fragment_Message extends Fragment {

    TextView textview_message;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_messagebox, container, false);
        textview_message = (TextView) view.findViewById(R.id.fragment_textview_message);
        textview_message.setText("test");
        return view;
    }

    public void set_message_success(String text) {
        textview_message.setText(text);
    }
}

And the relevant lines from the Activity class:

FragmentManager frag_manager    = getFragmentManager();
FragmentTransaction transaction = frag_manager.beginTransaction();
Fragment_Message fragment       = new Fragment_Message();
fragment.set_message_success(message_green);
transaction.add(R.id.home_fragment_container, fragment, "Fragment");
transaction.commit();

home_fragment_container is a RelativeLayout in my main_activity.xml, fragment_textview_message is the textView in the fragment_messagebox.xml, just to let you know, what these are.

The NullPointerException is caused in set_message_success(). Any Ideas?

like image 992
Peder Avatar asked Dec 05 '25 19:12

Peder


1 Answers

You are creating a fragment but the creation cycle is not executed. This line :

Fragment_Message fragment = new Fragment_Message();

does NOT automatically calls onCreateView, thus your text view is not initialized (is null) and when you try to set its text with the following line:

fragment.set_message_success(message_green);

you get the exception since the text view member is not initialized so either initialize the text view in a constructor or define the fragment in the desired layout.

Look here for a detailed information

like image 149
giorashc Avatar answered Dec 08 '25 08:12

giorashc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!