setText from a fragment of another activity that has nothing to do with fragment
I want to set a textView
in a fragment of another activity, this activity is not a mainactivity
, has a fragment transaction
…
Have tried some of the methods in other related articles related to my issue but get an error…
This is the method I received
from another activity in the fragment
fragment A
public class FragmentA extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ProgressDialog pDialog = new ProgressDialog(getContext());
pDialog.setCancelable(false);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Inflating view layout
View layout = inflater.inflate(R.layout.fragment_A, container, false);
Put Data to id fragment
valueName = (TextView) layout.findViewById(R.id.valueNameNav);
valueStatus = (TextView) layout.findViewById(R.id.valueStatusNav);
}
public void setText(String name, String status){
valueName = (TextView) getView().findViewById(R.id.valueNameNav);
valueName.setText(name);
valueStatus = (TextView) getView().findViewById(R.id.valueStatusNav);
valueStatus.setText(status);
}
}
This is how I call the setText
method in the fragment of the activity
String editValueName= editName.getText().toString();
String lastStatus = valueStatus.getText().toString();
FragmentA mFragment = (FragmentA )
getSupportFragmentManager().findFragmentById(R.id.fragment_A);
mFragment.setText(editValueName, lastStatus);
But there was such an error
java.lang.NullPointerException: Attempt to invoke virtual method ‘void
com.example.study.fragment.fragmentA.setText(java.lang.String,
java.lang.String)’ on a null object reference
100% sure that there is a data string on the string getText
Solution
Create a FrameLayout in your activity with an id container
and a height width of MATCH_PARENT
Then add fragments to your activity like this
FragmentA newFragment = new FragmentA ();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.container, newFragment).commit();
Then set your text
String editValueName= editName.getText().toString();
String lastStatus = valueStatus.getText().toString();
newFragment .setText(editValueName, lastStatus);