android studioで、クリックするたびに数の減るアプリを作っています。最初は1000から始まって、クリックするたびに1ずつ減っていくように作っています。数の減る動作は実装できるのですが、その値を、アプリを再起動した後も引き継ぐようにしたいのです。SharedPreferencesを使ったのですが、今の書き方だと画面上では数は減っているのですが、ボタンをクリックするとまた最初から(1000)に戻ってしまいます。どうかアドバイスいただけませんでしょうか。
ちなみにActivity上ではTextview(数を表示)、ボタン(押すとCountScoreメソッドが動く)の二つを配置しています。
public class MainActivity extends ActionBarActivity {
public int x = 1000; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); loadCount(); } public void CountScore(View view) { //クリックの処理 x--; TextView tv = (TextView) findViewById(R.id.myCount); tv.setText(String.valueOf(x)); saveCount(); } public void saveCount(){ //値の保存 SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor editor = sp.edit(); editor.putInt("int" , x); editor.apply(); } public void loadCount() { // 読み込み TextView tv = (TextView) findViewById(R.id.myCount); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); tv.setText(String.valueOf(sp.getInt("int", x))); }
}
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/04/09 08:47