-1

I have an activity, which instantiates 4 different fragments based on button clicks. I have to pass additional values to my fragment which is currently active.

Initially, when I pass values via setArguments, the values are being passed. But 2nd time the values are not passed to Fragment.

I tried to Log and put breakpoints in onCreate and onCreateView methods, but these methods are not being called at all 2nd time.

Here is my code

Code in Activity

Bundle bundle = new Bundle();
bundle.putInt("from", "1");
bundle.putString("label","One");

MyFragment1 myFragment1 = new MyFragment1();
myFragment1.setArguments(bundle);
getSupportFragmentManager()
.beginTransaction()
.addToBackStack(null)
.replace(R.id.fragment1, myFragment1)
.commitAllowingStateLoss();

Code in Fragment

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    Bundle b = getArguments();
    if(b!=null)
    { 

    }


}
Anirudh
  • 2,767
  • 5
  • 69
  • 119
  • `public void onCreate(@Nullable Bundle savedInstanceState) {` intead of this try to get inside `public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {` – Hasmukh Kachhatiya Nov 23 '17 at 11:32
  • You can find a solution to the similar problem here: https://stackoverflow.com/questions/41454596/how-to-search-in-listview-from-toolbar-in-fragment/41463851#41463851 – Hitesh Pamnani Nov 23 '17 at 11:33

2 Answers2

0

From Activity

Bundle bundle = new Bundle();
bundle.putInt("from", "1");
bundle.putString("label","One");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);

and in Fragment onCreateView method:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    String label = getArguments().getString("label");    
    int i=getArguments().getInt("from"); 
    return inflater.inflate(R.layout.fragment, container, false);
}
Jayesh
  • 131
  • 5
0

Found the solution

I gave this line of code in onCreate in Activity.

MyFragment1 myFragment1 = new MyFragment1();

I had to reinstatitate before passing it to the fragment.

Anirudh
  • 2,767
  • 5
  • 69
  • 119