Send Data From One Activity To A Fragment On A Second Activity
I have a main activity with a navigation drawer and several fragments and a secondary activity that collects some data that I store on a string called 'endpoints'. I'm trying to se
Solution 1:
Ok, this is how your Constants class should look like.
publicclassConstants {
publicstaticConstants constants=null;
publicstaticConstantsshared(){
if (constants==null){
constants = newConstants();
}
return constants;
}
publicstaticString endpoint;
publicstaticStringgetEndpoint() {
return endpoint;
}
publicstaticvoidsetEndpoint(String endpoint) {
Constants.endpoint = endpoint;
}
}
Now, in the second activity, do this:
Constants.shared().setEndpoint(endpoint);
Intent intent = newIntent(Secondary.this,Main.class);
startActivity(intent);
And in your Fragment class, do this:
@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Stringendpoint= Constants.shared().getEndpoint;
ViewrootView= inflater.inflate(R.layout.fragment_overview, container, false);
TextViewtextView= (TextView) rootView.findViewById(R.id.overviewTV);
textView.setText(endpoint);
return rootView;
}
Solution 2:
If your Main activity is the central point that delegates data and work to fragments I would also store the information there. If you have a member variable in your Main activity to store your endpoint than each of the fragments can access it via:
((Main) getActivity()).setEndpoint(endpoint)
((Main) getActivity()).getEndpoint()
This way your Main activity is the controller.
Solution 3:
You don't even have to use intent.putExtra to complete this. You can simply introduce some static variables in your project.
Make a class called Constants.
in that class, make a variable
publicstaticString endpoint;
Then, in your Secondary activity, instead of putExtra, simply do this:
Constants.endpoint = "your value";
Then, in your fragment simply do this:
TextViewtextView= (TextView) rootView.findViewById(R.id.overviewTV);
textView.setText(Constants.endpoint);
Post a Comment for "Send Data From One Activity To A Fragment On A Second Activity"