I have an app with 1 Activity and 3 Fragments.
In the Activity I have an adapter, into which I store log messages -
MainActivity.java (keeps the adapter with strings):
private ArrayAdapter<String> mLogListAdapter;
public void onCreate(Bundle savedInstanceState) {
.....
mLogListAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
android.R.id.text1);
if (savedInstanceState == null) {
MainFragment fragment = new MainFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("LOG", (Serializable) mLogListAdapter);
//bundle.putParcellable("LOG", (Parcellable) mLogListAdapter);
getFragmentManager().beginTransaction()
.replace(R.id.root, fragment, "main")
.commit();
}
}
And I would like to use that adapter in my first fragment -
MainFragment.java (should display a list with log strings):
private ListView mLogList;
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
.........
mLogList = (ListView) view.findViewById(R.id.logList);
mLogList.setChoiceMode(ListView.CHOICE_MODE_NONE);
// THIS DOES NOT WORK
ListAdapter adapter =
(ListAdapter) savedInstanceState.getSerializable("LOG");
mLogList.setAdapter(adapter);
return view;
}
Unfortunately, this does not work (app crashes).
I have also tried adding a public method to the Fragment and calling it in the Activity - but then mLogList
is null and I get NPE (as the mLogList
is created later - not in the constructor, but in onCreateView
method):
MainActivity.java:
if (savedInstanceState == null) {
MainFragment fragment = new MainFragment();
fragment.setAdapter(mLogListAdapter);
getFragmentManager().beginTransaction()
.replace(R.id.root, fragment, "main")
.commit();
}
MainFragment.java:
public void setAdapter(ListAdapter adapter) {
mLogList.setAdapter(adapter); // GIVES NPE
}
Please advise how to pass my adapter to the Fragment.
UPDATE:
I've tried Exception Lover's suggestion (thanks +1), but get this error:
The method putParcelableArrayList(String, ArrayList) in the type Bundle is not applicable for the arguments (String, ArrayAdapter)
And I am not, sure which of the quickfix suggestions should I take:
Also I wonder, why can't savedInstanceState
be used - do I really need to create a new Bundle
object when passing data from Activity to Fragment?