Search code examples
androidandroid-fragmentsbundleandroid-adapter

Bundle returning Null when called in fragment


I am trying to pass string from Adapter to fragment in Bundle bu ti'm getting null in my Fragment

Here is my code to add string to Bundle

            Bundle bundle=new Bundle();
            bundle.putString("id",expense_id);
            AddExpenseFragment fragment=new AddExpenseFragment();
            fragment.setArguments(bundle);
            UiActivity.startAddExpense(context);

this is my code to retrieve to Bundle value in Fragment

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

    super.onCreateView(inflater, container, savedInstanceState);
    View view=inflater.inflate(R.layout.activity_fragment_add_expense,container,false);
    String id=this.getArguments().getString("id");
    return view;
}

and i'm passing bundle value from My recyclerView Adapter class


Solution

  • The problem is simple here. You are creating a fragment and setting data to it which is fine,

    AddExpenseFragment fragment=new AddExpenseFragment();
    fragment.setArguments(bundle);
    

    But the problem is in your

    UiActivity.startAddExpense(context);
    

    you must be replacing with a new instance of the AddExpenseFragment as you are no where passing the newly created fragment instance (with the arguments set to it) to the startAddExpense() method.

    The solution is simple, just pass the newly created fragment object to the startAddExpense() like this,

    UiActivity.startAddExpense(context, fragment);
    

    and then inside the method replace or add this new fragment and do not instantiate any new fragment object.