hi Я хочу сохранить свою высокую оценку за счет общих настроек. но когда я перехожу к другому действию, а затем получаю такую же активность, моя высокая оценка снова начинается с нуля. Я знаю его просто, но я не знаю, какую ошибку я делаю. вот пример кода.Сохранение значений в общих предпочтениях
private static final String FORMAT = "%02d:%02d:%02d";
int count = 0, high;
int seconds , minutes;
SharedPreferences sharedPreferences;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
sharedPreferences = getPreferences(MODE_PRIVATE);
int savedPref = sharedPreferences.getInt("HighScore", 0);
final TextView counter=(TextView)findViewById(R.id.taptimes);
final TextView countdown=(TextView)findViewById(R.id.countdown);
final TextView highScore = (TextView)findViewById(R.id.highScore);
final Button b1=(Button)findViewById(R.id.keypress);
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
countClick();
}
private void countClick() {
// TODO Auto-generated method stub
count++;
counter.setText(String.valueOf(count));
if (count > high){
highScore.setText(Integer.toString(count));
high = count;
sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("HighScore", high);
editor.commit();
}
}
});
new CountDownTimer(10000, 1000) {//CountDownTimer(edittext1.getText()+edittext2.getText()) also parse it to long
public void onTick(long millisUntilFinished) {
countdown.setText("Time remaining: " + millisUntilFinished/1000);
//here you can have your logic to set text to edittext
}
public void onFinish() {
countdown.setText("Time Over!");
b1.setEnabled(false);
}
}
.start();
}
@Override
public void onBackPressed()
{
super.onBackPressed();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
для меня этот код работает отлично.Если я запускаю это действие несколько раз, я могу получить сохраненное значение. Возможно, вы сбросите значение во второй активности. – thedarkpassenger
Вторая активность не имеет ничего общего с этим .. Я не знаю, почему бы не сохранить значение –
Где вы используете savedPref? Извините, я нахожусь на мобильном экране, и я не вижу ничего лучше, но я думаю, что вы не инициализируете счет – FranMowinckel