Android Studio Clicker App中的SharedPreferences无效

时间:2017-10-25 01:24:31

标签: java android sharedpreferences

我正在创建一个简单的点击程序。我点击梨图片然后它增加1并显示。我想保存这个号码,这样他们就可以点击然后完全退出应用程序,当他们返回相同的号码时,他们仍然在那里。这是我的代码但是当我重新启动应用程序时它仍然没有保存pears int。

CODE:

    package pearclicker.pearclicker;

    import android.content.SharedPreferences;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.ImageButton;
    import android.widget.TextView;

    public class MainActivity extends AppCompatActivity {

    ImageButton imageButtonPear;
    TextView showValue;
    int pears;

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

        showValue = (TextView) findViewById(R.id.countText);
    }


    public void PearIncrease(View v) {
        SharedPreferences pref = getApplicationContext().getSharedPreferences("PearCount", MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        editor.putInt("pearCount", pears);
        pears++;
        if (pears == 1) {
        showValue.setText(pears + " pear");
            editor.putInt("pearCount", pears);
            editor.apply();
        }
        else {
            showValue.setText(pears + " pears");
            editor.putInt("pearCount", pears);
            editor.apply();
        }
    }

}

1 个答案:

答案 0 :(得分:1)

单击按钮增加梨的值时,您的代码正常。但是你在onCreate()中没有做任何事情,所以你认为SharedPreference在重新启动应用时没有存储pear的值。

为此,您需要对代码进行一些修改。

public class MainActivity extends AppCompatActivity {

    ImageButton imageButtonPear;
    TextView showValue;
    int pears = 0;

    SharedPreferences pref;
    SharedPreferences.Editor editor;

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

        pref = getApplicationContext().getSharedPreferences("PearCount", MODE_PRIVATE);

        showValue = (TextView) findViewById(R.id.countText);

        pears = pref.getInt("pearCount", 0); // This will get the value of your pearCount, It will return Zero if its empty or null.
        showValue.setText(pears + " pears");
    }


    public void PearIncrease(View v) {
        editor = pref.edit();
        pears++;
        showValue.setText(pears + " pears");
        editor.putInt("pearCount", pears);
        editor.apply();
    }
}