我有一个加载在ViewPager
:
public class mFragment extends Fragment {
public ArrayList<String> mArrayList;
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putStringArrayList("KEY", mArrayList);
super.onSaveInstanceState(outState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (savedInstanceState != null) {
mArrayList = savedInstanceState.getStringArrayList("KEY");
} else {
mArrayList = new ArrayList<>();
}
...
}
}
和我的活动类的onCreate()
方法内部:
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mFragment currentFragment = (mFragment) mFragmentPagerAdapter.getItem(mViewPager.getCurrentItem());
currentFragment.mArrayList.clear();
}
});
我可以点击ArrayList
清除mButton
,但在更改屏幕方向后,我收到以下错误:
06-14 17:35:08.274 1995-1995/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: a.wallpaper, PID: 1995
java.lang.NullPointerException: Attempt to invoke virtual method 'void java.util.ArrayList.clear()' on a null object reference
at a.wallpaper.MainActivity$6.onClick(MainActivity.java:123)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
答案 0 :(得分:0)
基于this answer,在MediumText { text: "Username: ";Layout.fillWidth:true;Layout.preferredWidth: parent.width/2}
类中覆盖instantiateItem()
方法后,错误就消失了:
mFragmentPagerAdapter