Android 获取片段中的Nullpointerexception

Android 获取片段中的Nullpointerexception,android,android-fragments,Android,Android Fragments,我正在开发一个应用程序,其中我在一个活动上附加了5个片段。一切都很好,但当我把我的应用程序从任何片段放到后台,一段时间后,当我的应用程序恢复时,它崩溃了。我的活动引用为空。这是我的密码 这是Activty中的代码,我将从中附加片段 FragmentManager fragmentManager = getSupportFragmentManager(); searchFragment = SearchFragment.newInstance(MainBaseActivity.this

我正在开发一个应用程序,其中我在一个活动上附加了5个片段。一切都很好,但当我把我的应用程序从任何片段放到后台,一段时间后,当我的应用程序恢复时,它崩溃了。我的活动引用为空。这是我的密码

这是Activty中的代码,我将从中附加片段

   FragmentManager fragmentManager = getSupportFragmentManager();
   searchFragment = SearchFragment.newInstance(MainBaseActivity.this);
   fragmentTransaction = fragmentManager.beginTransaction();
   fragmentTransaction.add(R.id.frameLayoutMain, searchFragment, "SearchFragment");
   fragmentTransaction.commit();
这是我的片段类

   public static SearchFragment newInstance(MainBaseActivity mainBaseActivity) {

    fragment = new SearchFragment();
    fragment.mainBaseActivity = mainBaseActivity;
    fragment.inflater = (LayoutInflater) mainBaseActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    fragment.myApplication = ((MyApplication) mainBaseActivity.getApplicationContext());
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.search_fragment, container, false);

    preferences = mainBaseActivity.getSharedPreferences(Constant.CHAI_APP, Context.MODE_PRIVATE);  // here i get null pointer
    editor = preferences.edit();

    return view;
}

片段具有
getActivity()
方法来检索它所附加到的活动。使用它代替
mainBaseActivity

系统可以在不同时间杀死并重新创建片段。您不能信任在
newInstance()
中执行的初始化类型-重新创建片段时,字段将不会初始化

删除以下初始化:

fragment.mainBaseActivity = mainBaseActivity;
fragment.inflater = (LayoutInflater) mainBaseActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
fragment.myApplication = ((MyApplication) mainBaseActivity.getApplicationContext());
当您需要访问托管活动或
应用程序时,请在片段中使用
getActivity()

对于充气机,一个已作为参数传入
onCreateView()
。不用自己去拿


(要将参数传递给在片段复制过程中持续存在的片段,请使用
setArguments()

。我真的很喜欢有问题的人。所以请发布它。我使用了它,但得到的是null,我看不到它在任何地方被使用,我的意思是我在mainbaseactivity的位置使用了getActivity(),但得到的是null指针。在这种情况下,你在哪里使用它?Inside onCreateView还是Inside newInstance?Inside onCreateView()谢谢你的建议我会照你的建议做。