Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

Fragment_Messagefragment=newFragment_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

Solution 2:

The problem apparently is the lifecycle of the fragment. When I add a fragment (done in the activity's onCreate()) and define it's textView-text in the fragment's onCreateView(), the fragment will be displayed without problems. But accessing the fragment's textView in the activity's onCreate() fails, because - I guess - the fragment is not attached yet.

So I added the fragment in the activity's onCreate() and changed the fragment's textView-text in the activity's onResume(), where (as I understand it) the fragment should be attached. Furthermore, it helps to use executePendingTransactions(). My now working code:

Home.java

FragmentManager     frag_manager;
FragmentTransaction transaction;
Fragment_Message    fragment;


@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    frag_manager    = getFragmentManager();
    transaction     = frag_manager.beginTransaction();
    fragment        = newFragment_Message();

    transaction.add(R.id.home_fragment_container, fragment, "Fragment_Messagebox");
    transaction.commit();
}


@OverrideprotectedvoidonResume() {
        frag_manager.executePendingTransactions();          
        fragment.set_message_success("a message");
}

Fragment_Message.java

publicclassFragment_MessageextendsFragment {

    TextView textview_message;
    View view;

    publicFragment_Message() {}


    @OverridepublicViewonCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_messagebox, container, false);
        return view;
    }


    publicvoidset_message_success(String text) {
        textview_message = (TextView) view.findViewById(R.id.fragment_textview_message);
        textview_message.setText(text);
    }
}

Post a Comment for "Nullpointerexception When Accessing A Fragment's Textview In An Activity"