Search code examples
javaandroidandroid-fragmentsandroid-viewpagerandroid-sharedpreferences

How to save EditText value in Shared Preferences when user swipe fragment in viewpager?


I have multiple fragment in viewpager and each fragment have almost ten editext so I want to save all value in shared preference. when user swipe fragment one then data of fragment1 will saved in shared preference and same for all fragment.

public void user(String EditText1, String EditText2){

        // Storing data in pref
        editor.putString(value1, EditText1);
        editor.putString(value2, EditText2);

        // commit changes
        editor.commit();
    }

Below is my code to get edittext value to save in shared preference -

pager.setOffscreenPageLimit(9);

        pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {


            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

                Fragment1 f1 = new Fragment1();
                EditText1= f1.txtEditText1.getText().toString();
                EditText2= f1.txtEditText2.getText().toString();

                session.user(EditText1, EditText1);

            }
        });

When I fill all edit text on first fragment and when I swipe i am getting below error -

java.lang.NullPointerException: Attempt to invoke interface method 'android.content.SharedPreferences$Editor `android.content.SharedPreferences$Editor.putString(java.lang.String, java.lang.String)' on a null object reference`

Solution

  • Variable editor is null inside constructor of User class. That's why you are getting crash.

    Also onPageScrollStateChanged - is bad place for doing thing like that, because it will be called many times during one fragment swipping. Better to use onPageScrolled.

    Also there is no sense to create fragment in order to save something, you need to use fragment's instance that was visible for user. Check how to get fragment by position.