How do I set counter in SharedPreferences to save and retrieve data from TextView with button click

安稳与你 提交于 2019-12-25 07:50:08

问题


I have a problem with shared preferences for my Android app. It saves data and also retrieves but wont work with counter.

When I click the button, it increments by 0.0005 in TextView, so SharePref must be saved in button event. Now when I restart the app it retrieves it but now on clicking button it gets same as counter does. After restarting app then after clicking it gets back as counter starts. It means that shared preferences data is somehow lost after clicking button.

public class MainActivity extends AppCompatActivity {

    Button btn1;
    TextView t1;
    float counter = 0;
    float adding = (float) 0.0005;

    SharedPreferences sharedpreferences;

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

     t1 = (TextView)findViewById(R.id.textView);

        sharedpreferences = getSharedPreferences("MyPREFERENCES", Context.MODE_PRIVATE);
        t1.setText(String.valueOf(sharedpreferences.getFloat("key",0)));

    }

    public void AdButton(View v)     //Button Onclick
    {
        counter = counter+adding;
        strCounter = Float.toString(counter);
        t1.setText(strCounter);

       sharedpreferences = getSharedPreferences("MyPREFERENCES", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.putFloat("key", counter);
        editor.commit();
    }

}

回答1:


As I understands from your words, you want to save counter value is Shared Preferences and retrieve it again when App starts then on button click, you will increment it and save it again in Shared Preference. correct?

Simply, what you did is when app starts, you show the saved value (if exists) on the text view but you don't keep it in counter! so counter is zero

you have to keep it in counter after retrieving, add this line in onCreate after or before showing the value on textview.

counter = sharedpreferences.getFloat("key",0);



回答2:


You forgot to retrieve the value of counter before adding it again. Just use this :

public void AdButton(View v)     //Button Onclick
{
    sharedpreferences = getActivity().getSharedPreferences("MyPREFERENCES", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedpreferences.edit();
    counter = sharedpreferences.getFloat("key",0);
    counter = counter + adding;
    String strCounter = Float.toString(counter);
    t1.setText(strCounter);

    editor.putFloat("key", counter);

    editor.commit();
}


来源:https://stackoverflow.com/questions/42166398/how-do-i-set-counter-in-sharedpreferences-to-save-and-retrieve-data-from-textvie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!