我用 写了一个活动ViewPager
,它在 anAsyncTask
执行后被填充。每个TestDataObject
都与相关的TestFragment
. 当屏幕旋转时,应用程序由于NullPointerException
内部onCreateView
方法而崩溃。我相信这是因为ViewPager
/AdapteronSaveInstanceState
方法,当数据尚不可用时,onCreateView
尝试在数据加载之前恢复数据。AsyncTask
我可以只if
使用 onCreateView 代码,但我觉得它不是一个正确的解决方案,因为 ViewPager 中的片段数量可能会有所不同,因此它最终可能会做不必要的工作:恢复更改后的 viewpager 内容,然后替换为初始内容。在这种情况下,onSaveInstanceState 似乎过于有害。据推测,我可以扩展 ViewPager 或 Adapter 以取消保存过程——我也觉得这很奇怪。
你有什么更好的建议可以提供吗?
public class MainActivity extends LoggerActivity {
private ArrayList<TestDataObject> mDataObjects = new ArrayList<MainActivity.TestDataObject>();
private ViewPager mViewPager;
private TestFragmentAdapter mViewPagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPagerAdapter = new TestFragmentAdapter(
getSupportFragmentManager(), mDataObjects);
mViewPager.setAdapter(mViewPagerAdapter);
new TestAsyncTask().execute();
}
private class TestAsyncTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mDataObjects.add(new TestDataObject());
mDataObjects.add(new TestDataObject());
mDataObjects.add(new TestDataObject());
mViewPagerAdapter.notifyDataSetChanged();
}
}
public static class TestFragment extends Fragment {
private TestDataObject mDataObject;
public static TestFragment getInstance(TestDataObject obj) {
TestFragment f = new TestFragment();
f.mDataObject = obj;
return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// layout.find...
mDataObject.toString();
return inflater.inflate(R.layout.fragment_test, null, false);
}
}
public static class TestFragmentAdapter extends FragmentStatePagerAdapter {
private List<TestDataObject> mDataObjects;
public TestFragmentAdapter(FragmentManager fm, List<TestDataObject> objs) {
super(fm);
mDataObjects = objs;
}
@Override
public Fragment getItem(int position) {
return TestFragment.getInstance(mDataObjects.get(position));
}
@Override
public int getCount() {
return mDataObjects == null ? 0 : mDataObjects.size();
}
}
public static class TestDataObject {
}
}