The*_*Dev 5 android savestate android-fragments
我最近将我的应用程序从基于活动的应用程序转换为基于片段的应用程序。这是一个保持得分的应用程序,当我进行一项活动时,我很容易保存和恢复得分。但是,这似乎并不是一个片段。这是我的代码:
@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();
}
}
Run Code Online (Sandbox Code Playgroud)
I used this exact same code successfully on an activity in onRestoreInstanceState
rather than onActivityCreated
and without the try/catch. The problem is I'm getting null pointer errors an time I try and pull something from the bundle. I can see saving state in the log, and then onActivityCreated, but onActivityCreated doesn't seem to be getting the stuff put in the bundle by onSavedInstanceState. I just get a null pointer on every line that calls savedInstanceState.getAnything()
. However, from my reading, onCreate
, onCreateView
, and onActivityCreated
all use the same bundle. I have tried moving the code to the other two with no luck.
我最终想出了一个相当棘手的解决方法。对此并不感到兴奋,因为它实际上并没有解决核心问题。如果有人可以帮助我找到这一点,我很乐意接受这个答案。
也就是说,我只是使用 Activity 的 onSaveInstanceState 和 onRestoreInstanceState 来保存和恢复片段数据。
归档时间: |
|
查看次数: |
4070 次 |
最近记录: |