Avinash
Avinash

Reputation: 109

Getting Nullpointerexception in fragment

I am working on App where i am attaching 5 fragments on an activity. Everything is working great but when i put my app in background from any fragment and after some time when my app resumes it crashes. I get reference of my Activty as null. here is my code

This is code in Activty from where i am attaching fragment

   FragmentManager fragmentManager = getSupportFragmentManager();
   searchFragment = SearchFragment.newInstance(MainBaseActivity.this);
   fragmentTransaction = fragmentManager.beginTransaction();
   fragmentTransaction.add(R.id.frameLayoutMain, searchFragment, "SearchFragment");
   fragmentTransaction.commit();

And this is my Fragment class

   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;
}

Upvotes: 1

Views: 133

Answers (2)

laalto
laalto

Reputation: 152807

Fragments can be killed and recreated by the system at various times. You cannot trust the kind of initialization you do in your newInstance() - when the fragment is recreated, the fields won't be initialized.

Remove these initializations:

fragment.mainBaseActivity = mainBaseActivity;
fragment.inflater = (LayoutInflater) mainBaseActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
fragment.myApplication = ((MyApplication) mainBaseActivity.getApplicationContext());

and use getActivity() in your fragment when you need to access your hosting activity or the Application.

For inflater, one is already passed in as an argument to onCreateView(). No need to fetch it yourself.

(To pass params to a fragment that persist over fragment recreation, use setArguments().)

Upvotes: 1

Blackbelt
Blackbelt

Reputation: 157437

Fragment has the getActivity() method to retrieve the activity to which it is attached. Use it in place of mainBaseActivity

Upvotes: 1

Related Questions