-1

I want to send intent from activity to fragment. I know how to send from fragment to activity just like this

Intent chatIntent = new Intent(getContext(), ChatActivity.class);
                                            chatIntent.putExtra("user_id", user_id);
                                            chatIntent.putExtra("user_name", userName);
                                            startActivity(chatIntent);

but now i want to send from activity to fragment. I don't necessarily need to start the fragment i just want to make one of the id in my activity accessible in my fragment.

Eric
  • 157
  • 2
  • 17

2 Answers2

3

From your activity, you send your data, using bundle:

Bundle newBundle = new Bundle();
newBundle.putString("key", "text");
YourFragment objects = new YourFragment();
objects.setArguments(newBundle);

Your fragment class in onCreateView function:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
    if(getArguments() != null){
        String yourText = getArguments().getString("key");  
    }
    return inflater.inflate(R.layout.your_fragment, container, false);
}`
savepopulation
  • 11,736
  • 4
  • 55
  • 80
Ogulcan Ucarsu
  • 236
  • 2
  • 5
2

Passing the data from activity to fragment

Bundle bundle = new Bundle();
bundle.putString("params", "String data");
// set MyFragment Arguments
MyFragment fragment = new MyFragment();
fragment.setArguments(bundle);

Receiving the data in the fragment

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString("params");
        }
    }