Reputation: 185
I have this issue of sending some data back and forth between a fragment and its container activity, I succeeded in doing it. What puzzles me is sending my data from the fragment to the activity, at first I implemented OnResume()
, OnStop()
and sent the data through an intent and that created an infinite loop so I removed them. Then I did setRetainInstance(true)
and it worked and gave me the wanted behavior.
My Question is How my data are really being sent and where in the fragment lifecycle ?
Upvotes: 1
Views: 114
Reputation: 21756
You can also achieve this by using Interface
, using an EventBus
like LocalBroadcastManager
, or starting a new Activity
with an Intent
and some form of flag
passed into its extras
Bundle or something else.
Here is an example about using Interface:
1. Add function sendDataToActivity()
into the interface (EventListener
).
//EventListener.java
public interface EventListener {
public void sendDataToActivity(String data);
}
2. Implement this functions in your MainActivity
.
// MainActivity.java
public class MainActivity extends AppCompatActivity implements EventListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void sendDataToActivity(String data) {
Log.i("MainActivity", "sendDataToActivity: " + data);
}
}
3. Create the listener in MyFragment
and attach
it to the Activity
.
4. Finally, call function using listener.sendDataToActivity("Hello World!")
.
// MyFragment.java
public class MyFragment extends Fragment {
private EventListener listener;
@Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
if(activity instanceof EventListener) {
listener = (EventListener)activity;
} else {
// Throw an error!
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_my, container, false);
// Send data
listener.sendDataToActivity("Hello World!");
return view;
}
@Override
public void onDetach() {
super.onDetach();
listener = null;
}
}
Hope this will help~
Upvotes: 1
Reputation: 985
The Right approach is to use Interfaces. Don't use onStop or setRetainInstance()
See this. It will solve you problem. Pass data from fragment to actvity
Upvotes: 1