Search code examples
androidandroid-fragmentsandroid-activityandroid-bundle

How to get data from activity to fragment in android?


I am using Navigation Drawer in my project and the "Add" feature is in an activity which is called by fab. I need to get the data from the Activity to the Fragment.

I have already tried with bundle and the app crashes.

In my activity, AddTodoActivity.java file ->

date.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //showDatePicker();
            Bundle bundle = new Bundle();
            bundle.putString("1", "From Activity");
            FragmentList fragobj = new FragmentList();
            fragobj.setArguments(bundle);

            Fragment fragment = new FragmentList();
            if (fragment != null) {
                FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction ft = fragmentManager.beginTransaction();
                ft.replace(R.id.screen, fragment);
                ft.commit();
            }

            finish();
        }
    });

And in myfragment, FragmentList.java file ->

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    Toast.makeText(this.getContext(),  this.getArguments().getString("1"), Toast.LENGTH_SHORT).show();
    ....

Solution

  • You have two instances of FragmentList there: fragobj and fragment.

    You use fragobj.setArguments(), but then pass fragment to the FragmentManager.

    I don't really know why you're doing that, but if you want to pass the arguments, you need to remove one of those instances, and set the arguments on the one that remains. I recommend just removing the fragment one:

    //...
    FragmentList fragobj = new FragmentList();
    fragobj.setArguments(bundle);
    
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction ft = fragmentManager.beginTransaction();
    ft.replace(R.id.screen, fragobj);
    fr.commit();
    //...
    

    The null-check on the Fragment is also unnecessary. There's no way it could possibly be null.