Pass values between Fragments, Activity

1) to send data from fragment to activity

Intent intent = new Intent(getActivity().getBaseContext(), TargetActivity.class);
intent.putExtra("message", message);
getActivity().startActivity(intent);

2) to receive this data in Activity:

Intent intent = getIntent();
String message = intent.getStringExtra("message");


3) to send data from activity to another activity follow normal approach

Intent intent = new Intent(MainActivity.this, TargetActivity.class);
intent.putExtra("message", message);
startActivity(intent);

4) to receive this data in Activity

Intent intent = getIntent();
String message = intent.getStringExtra("message");

5) from Activity you can send data to Fragment with intent as:

Bundle bundle = new Bundle();
bundle.putString("message", "From Activity");
//set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);

6) and to receive in Fragment onCreateView method:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    String strtext = getArguments().getString("message");
    return inflater.inflate(R.layout.fragment, container, false);
}

From here.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s