Ashwini Bhat
Ashwini Bhat

Reputation: 500

How to pass intent from activity to fragment in Android

Hello am new to Android how to give intent from Activity to fragment? I know from Fragment to Activity like this

Intent intent=new Intent(getActivity(),nextActivity.class)
StartActivity(intent);

But I want from Activity to Fragment.

Upvotes: 0

Views: 27833

Answers (3)

Ciprian
Ciprian

Reputation: 2899

You cannot pass the intent to the fragment, what you can do is get the data you have in the intent and pass it to the fragment. The recommended way to do that is to use the newInstance pattern. So in the fragment you'll have this:

    public static MyFragment newInstance(@NonNull final String someId) {
        final MyFragment fragment = new ProfileFragment();
        final Bundle args = new Bundle();
        args.putString(Const.KEY_SOME_ID, someId);

        fragment.setArguments(args);

        return fragment;
    }

To create the fragment of course you'll call that method.

String id = getIntent().getStringExtra(Const.KEY_ID);
MyFragment fragment = MyFragment.newInstance(id);

and to access it inside the fragment you need to get from arguments:

    Bundle args = getArguments();
    if (args != null) {
        myId = args.getString(Const.KEY_SOME_ID, "");
    }

Upvotes: 5

Durgesh
Durgesh

Reputation: 291

In Activity you set data in intent

Bundle bundle = new Bundle();
bundle.putString("dataKey", "Value");
YourFragmentClass fragmentObject = new YourFragmentClass();
fragmentObject .setArguments(bundle);
if(fragmentObject!=null){
        FragmentManager fm = getFragmentManager();
        fm.beginTransaction().add(R.id.container, fragmentObject).commit();
    }

In Fragment's onCreateView method you can get the data

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {

String activityData= getArguments().getString("dataKey");  

return inflater.inflate(R.layout.fragment, container, false);

}

Upvotes: -1

Chirag Savsani
Chirag Savsani

Reputation: 6140

Currently I am working on Fragment.
use this code.

Fragment fragment =  new YourFragmentName();
if (fragment != null) {
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
        }

Where content_frame is

<FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

in main layout

Upvotes: 0

Related Questions