Amr SubZero Amr SubZero - 5 months ago 23
Java Question

How to pass an ArrayList from Activity to a Fragment

What i'm trying to do is sending

ArrayList<String>
from Activity to ListFragment

So i can use the Fragments in a
TableLayout


It's not necessary to use ListFragment, i can use any type of Fragments, but i'm trying to get the idea.

Here's my MainActivity :

FragmentTransaction fragmentTransaction;

ArrayList<String> namesArray = new ArrayList<>();

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

namesArray.add("Android");
namesArray.add("Iphone");
namesArray.add("Windows Phone");

Bundle bundle = new Bundle();
bundle.putStringArrayList("valuesArray", namesArray);
namesFragment myFragment = new namesFragment();
myFragment.setArguments(bundle);

fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_container, new namesFragment());
fragmentTransaction.commit();

}


My ListFragment :

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

ArrayList<String> values = getArguments().getStringArrayList("valuesArray");

ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, values);

setListAdapter(adapter);
}


I've searched a lot, but i didn't find anything useful, and this code above gives me
Unfortunately app has stopped


So how can i achieve something like that?

Answer

You are instantiating your fragment twice :D

Just change u'r code to:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    namesArray.add("Android");
    namesArray.add("Iphone");
    namesArray.add("Windows Phone");
    Bundle bundle = new Bundle();
    bundle.putStringArrayList("valuesArray", namesArray);
    namesFragment myFragment = new namesFragment();
    myFragment.setArguments(bundle);
    fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.add(R.id.main_container, myFragment);
    fragmentTransaction.commit();
}