sharedpreferences is not saving the text value

Aswin Krizna :
**

I am trying to save the text variable using Sharedpreferences. I saved the variable by this code. But when I click the button the saved variable will go back to 0. I want to start counting from the saved value. please help me

**int counter = 0;

public static final  String SHARED_PREF="shared";
public static final String TEXT="text";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);

    counterView=findViewById(R.id.counterid);
    Btn=findViewById(R.id.button1);

    Btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            counter++;
            counterView.setText(Integer.toString(counter));

            SharedPreferences sp = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putString(TEXT,counterView.getText().toString());
            editor.commit();

        }

    });


    SharedPreferences sp = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
    String tValue = sp.getString(TEXT,"");
    counterView.setText(tValue);


}

}

Costin :

Considering the informations you've provided I think you needed to give the counter the value stored in SharedPreferences, to continue the count from that, when the button was pressed again. Try this:

 int counter = 0;
Button adBtn;
TextView counterView;
public static final  String SHARED_PREF="shared";
public static final String TEXT="text";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    counterView=findViewById(R.id.counterid);
    adBtn=findViewById(R.id.button1);

    adBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SharedPreferences counterSp = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
            String correctCounterValue = counterSp.getString(TEXT,"");
            counter = Integer.valueOf(correctCounterValue);
            counter++;
            counterView.setText(Integer.toString(counter));

            SharedPreferences sp = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putString(TEXT,counterView.getText().toString());
            editor.commit();

        }

    });


    SharedPreferences sp = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
    String tValue = sp.getString(TEXT,"");
    counterView.setText(tValue);


}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=300291&siteId=1