Reputation: 49
I have two fragments
and the first fragment has a recyclerview adapter
were i want to pass adapter position to another fragment on clicking
the recycler view
..
Fragment 1 code from recyclerview adapter
:
holder.address.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("Position of items...///", String.valueOf(position));
//For sending data between fragments
Bundle bundle = new Bundle();
bundle.putInt("Position", position);
StoreDetails storeDetails = new StoreDetails();
storeDetails.setArguments(bundle);
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, new StoreDetails())
.commit();
}
});
Fragment 2 code:
Bundle b = getArguments();
if(b != null)
{
b.getInt("Position");
}
else
{
Toast.makeText(getActivity(), "Oops sorry..!!", Toast.LENGTH_SHORT).show();
}
Upvotes: 2
Views: 1615
Reputation: 69689
you are adding
Bundle
inStoreDetails
Fragment
and your are passing new object ofStoreDetails
Fragment
you need to pass same object of your
StoreDetails
Fragment
in which you add theBundle
so change this as below code
use this
Bundle bundle = new Bundle();
bundle.putInt("Position", position);
StoreDetails storeDetails = new StoreDetails();
storeDetails.setArguments(bundle);
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, storeDetails)
.commit();
instead of this
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame,new StoreDetails())
.commit();
Upvotes: 4
Reputation: 1219
Try like this:
private Bundle bundle;
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this.bundle = getArguments();
if (bundle != null) {
bundle.getInt("Position");
} else {
Toast.makeText(getActivity(), "Oops sorry..!!", Toast.LENGTH_SHORT).show();
}
}
Upvotes: 0