Ahmed Ezzat Ahmed Ezzat - 3 months ago 18
Android Question

pass data to Fragment

I have an Activity and a simple fragment ,I try to use Bundle to pass data to the fragment, but the bundle is always null.
I can't figure out what is the problem?!

this is my Activity class

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


FragmentA fragmentA =new FragmentA();
Bundle bundle=new Bundle();
bundle.putString("name","Ahmed Ezzat");
fragmentA.setArguments(bundle);
}

public void showFragment(View view) {

FragmentA fragmentA=new FragmentA();
FragmentManager manager=getSupportFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.add(R.id.dumper,fragmentA,"fragment A");
transaction.commit();
}
}


and this is my fragment class

public class FragmentA extends Fragment {
TextView textView;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_a,container,false);

textView= (TextView) view.findViewById(R.id.tv_fragment);


Bundle bundle = this.getArguments();
String name = bundle.getString("name");
if (name!=null){
textView.setText(name);}

return view;
}


}

any help?

Answer

You never called setArguments in the showFragment method.

The Fragment in the onCreate method is never used.

You may try using the following code

 public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void showFragment(View view) {

        FragmentA fragmentA=new FragmentA();
        Bundle bundle=new Bundle();
        bundle.putString("name","Ahmed Ezzat");
        fragmentA.setArguments(bundle);

        getSupportFragmentManager()
            .beginTransaction()
            .add(R.id.dumper,fragmentA,"fragment A")
            .commit();
    }
}