Saturday 24 August 2013

Why is the fragment's setRetainInstance(true) method not working?

Why is the fragment's setRetainInstance(true) method not working?

I cannot seem to get my Fragment to retain its instance on an orientation
change.
Activity Class
public class MyActivity extends Activity
{
private MyFragment fragment;
public void onCreate(Bundle savedInstanceState)
{
if(savedInstanceState == null)
{
fragment = new MyFragment();
}
//null pointer exception on this line of code. fragment not being
retained.
getFragmentManager().beginTransaction().replace(R.id.fragment_container,
fragment).commit();
}
}
Fragment Class
public class MyFragment extends Fragment
{
private View view;
private CustomListViewAdapter adapter;
public ArrayList<HashMap<String, String>> arrHashMap;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
view = inflater.inflate(R.layout.fragment_screen, container, false);
if(arrHashMap != null)
{
ListView lv = (ListView) view.findViewById(R.id.fragment_lv);
adapter = new CustomListViewAdapter( (MyActivity)getActivity()
, arrHashMap);
lv.setAdapter(adapter);
lv.setOnItemClickListener((MyActivity)getActivity());
}
else
{
//some code to create arrHashMap variable
ListView lv = (ListView) view.findViewById(R.id.fragment_lv);
adapter = new CustomListViewAdapter( (MyActivity)getActivity()
, arrHashMap);
lv.setAdapter(adapter);
lv.setOnItemClickListener((MyActivity)getActivity());
}
return(view);
}
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
}
}
I know you are not supposed to use setRetainInstance(true) to retain UI
fragments, but I am not using the retained view or adapter, I simply care
about retaining the arrHashMap across orientation changes so I can reset
the adapter. Also the MyFragment itself is staying null even after
orientation change despite setRetainInstance(true) being set. Thank you.

No comments:

Post a Comment