What is wrong with onDestroyView() method?

464 Views Asked by At

I am trying to save values in my pref before fragment is destroyed but an error message says

android.support.v4.app.SuperNotCalledException: Fragment did not call through to super.onDestroyView()

here is my code

@Override
public void onDestroyView() {
    pref3.edit().clear().commit();
    for (int i = 0; i < movies1.size(); i++) {
        favouritemovies1.add(movies1.get(i));
        SharedPreferences.Editor editor3 = pref3.edit();
        editor3.putStringSet("favouritemovies", favouritemovies1);
        editor3.commit();
        Toast.makeText(getActivity(), "destroyed", Toast.LENGTH_SHORT).show();
        super.onDestroyView();

    }
}

when I comment for loop every thing works fine!

2

There are 2 best solutions below

0
A S M Sayem On BEST ANSWER

Just keep the super.onDestroyView(); out of the for loop and inside the @Override method like this:-

   @Override
    public void onDestroyView() {
        // or here 
        pref3.edit().clear().commit();
        for (int i = 0; i < movies1.size(); i++) {
            favouritemovies1.add(movies1.get(i));
            SharedPreferences.Editor editor3 = pref3.edit();
            editor3.putStringSet("favouritemovies", favouritemovies1);
            editor3.commit();
            Toast.makeText(getActivity(), "destroyed", Toast.LENGTH_SHORT).show();
    
        }
        super.onDestroyView();
    }
0
Jakir Hossain On

Remove super.onDestroyView(); from the loop and write it in the top like following.

@Override
public void onDestroyView() {
    super.onDestroyView();
    pref3.edit().clear().commit();
    for (int i = 0; i < movies1.size(); i++) {
        favouritemovies1.add(movies1.get(i));
        SharedPreferences.Editor editor3 = pref3.edit();
        editor3.putStringSet("favouritemovies", favouritemovies1);
        editor3.commit();
        Toast.makeText(getActivity(), "destroyed", Toast.LENGTH_SHORT).show();
        

    }
}