Search code examples
androidsharedpreferencesandroid-ondestroy

What is wrong with onDestroyView() method?


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!


Solution

  • 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();
        }