I recently converted my application from an activity-based application to a fragment-based application. This is a score app, and I could easily save and restore the score when it was a lesson. However, this does not work as a fragment. Here is my code:
@Override public void onSaveInstanceState(Bundle savedInstanceState){ super.onSaveInstanceState(savedInstanceState); if(t!=null&&flag==1){ savedInstanceState.putInt("time", t.getTimeLeft()); } else { savedInstanceState.putInt("time", 0); } savedInstanceState.putIntArray("score_array", points); savedInstanceState.putIntArray("position_array", spinnerPosition); savedInstanceState.putBooleanArray("checked_array", shouldBeChecked); flag = 0; Log.d("MyApp", "savingState"); } @Override public void onActivityCreated(Bundle savedInstanceState){ super.onActivityCreated(savedInstanceState); Log.d("MyApp", "onActivityCreated"); try { int timeLeft = savedInstanceState.getInt("time"); points = savedInstanceState.getIntArray("score_array").clone(); spinnerPosition = savedInstanceState.getIntArray("position_array").clone(); shouldBeChecked = savedInstanceState.getBooleanArray("checked_array").clone(); ((BaseAdapter) ((ListView)getView().findViewById(R.id.missionList)).getAdapter()).notifyDataSetChanged(); if(timeLeft!=0){ flag=1; this.getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); t = new TimerClass(timeLeft*1000, 1000); t.setViews((TextView)getView().findViewById(R.id.minuteView), (TextView)getView().findViewById(R.id.tenSecondView), (TextView)getView().findViewById(R.id.secondView), (Button)getView().findViewById(R.id.start_button)); ((Button)getView().findViewById(R.id.start_button)).setText(R.string.stop); t.start(); } } catch (Exception e) { e.printStackTrace(); } }
I used this exact code successfully for activity in onRestoreInstanceState , not onActivityCreated and without try / catch. The problem is that I get null pointer errors when I try to extract something from the package. I can see the save state in the log, and then onActivityCreated, but onActivityCreated does not seem to receive the stuff placed in the package by onSavedInstanceState. I just get a null pointer to every line that calls savedInstanceState.getAnything() . However, from my reading onCreate , onCreateView and onActivityCreated all use the same set. I tried translating the code to the other two without any luck.
source share