java - NullPointerException when accessing a Fragment's textView in an Activity -



java - NullPointerException when accessing a Fragment's textView in an Activity -

it seems mutual problem, after hours of trying random solutions provided answers similar questions, code still produces nullpointerexception when access fragment's textview activity.

i can include (and view) fragment when textview has predefined text or using settext() in oncreateview() of fragment class not using setter method (here set_message_success()).

this 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"); homecoming view; } public void set_message_success(string text) { textview_message.settext(text); } }

and relevant lines 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 relativelayout in main_activity.xml, fragment_textview_message textview in fragment_messagebox.xml, allow know, these are.

the nullpointerexception caused in set_message_success(). ideas?

you creating fragment creation cycle not executed. line :

fragment_message fragment = new fragment_message();

does not automatically calls oncreateview, text view not initialized (is null) , when seek set text next line:

fragment.set_message_success(message_green);

you exception since text view fellow member not initialized either initialize text view in constructor or define fragment in desired layout.

look here detailed information

java android-fragments nullpointerexception

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -