2016-12-27 3 views
-1

В моем новом приложении счетчик увеличивается при нажатии кнопки. Я хочу сохранить рекордер с sharedPreferences, поэтому оценка будет сохранена и показана при следующем запуске приложения. Проблема в том, что я действительно не работаю, даже с другими ответами на вопросы.android - сохранение int с sharedPreferences

package com.example.test; 

public class MainActivity extends ActionBarActivity { 

    public int score = 0; 
    public int highscore = 0; 
    TextView tvscore; 


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

     TextView tvhighscore= (TextView) findViewById(R.id.highscore); 
     tvscore = (TextView) findViewById(R.id.score); 
     Button count = (Button) findViewById(R.id.button1); 

     tvhighscore.setText(String.valueOf(highscore)); 

     SharedPreferences prefs = this.getSharedPreferences("score", Context.MODE_PRIVATE); 
     Editor editor = prefs.edit(); 
     editor.putInt("score", 0); 
     editor.commit(); 



    } 

    public void onClick (View view) { 
     score++; 
     tvscore.setText(String.valueOf(score)); 

     SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE); 
     int highscore = prefs.getInt("score", 0); 
    } 


} 
+0

необходимо сохранить счет в 'SharedPreferences' при нажатии кнопки –

+0

@ ρяσѕρєя K является правильным. Кроме того, убедитесь, что вы используете одно и то же имя для файла общих настроек. –

+0

Я не использую одноименное имя '' score''? –

ответ

0

Прежде всего, вам необходимо использовать тот же ключ для общих настроек при записи и запросе. Затем также в onclick вам нужно сохранить счет в prefs и не запросить его снова. Вот обновленный код:

public class MainActivity extends ActionBarActivity { 

     public int score = 0; 
     public int highscore; 
     TextView tvscore, tvhighscore; 

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

      tvhighscore= (TextView) findViewById(R.id.highscore); 
      tvscore = (TextView) findViewById(R.id.score); 
      Button count = (Button) findViewById(R.id.button1); 


      SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE); 
      highscore = prefs.getInt("high_score", 0); 
      tvhighscore.setText(String.valueOf(highscore)); 
     } 

     public void onClick (View view) { 
      score++; 
      tvscore.setText(String.valueOf(score)); 
      if (score > highscore) { 
       highscore = score; 
       SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE); 
       prefs.edit().putInt("high_score", highscore).apply(); 
       tvhighscore.setText(String.valueOf(highscore)); 
      } 
     } 
    } 
+0

Он работает, спасибо! –

0

У вас есть какие-то ошибки в коде

Первая ошибка в том, что вы используете разные имена для SP

SharedPreferences доступны через unique key. в вашем коде у вас есть два из них: myPrefsKey и myPrefsKey. Не забудьте использовать всегда то же самое или значение не будет найдено.

Во-вторых, вы используете два раза один и тот же ИНТ имя

Как в коде и в onclick методе вы литья int с тем же именем highscore. Это не допускается

Третий находится в логик:

Что вы делаете:

  • Сохранение значения на activity начала.
  • Чтение значения на button мыши

В то время как вы должны сделать следующее:

  • Считайте значение в onCreate методе с использованием коды GetInt вы используете внутри button мышей и установив textview's текст с Это.
  • Сохраните значение на button после его увеличения.

Таким образом, у вас будет действующий код.

Ниже приведен пример:

package com.example.test; 

public class MainActivity extends ActionBarActivity { 

    public int score = 0; 
    public int highscore = 0; 
    TextView tvscore; 
    SharedPreferences prefs; 

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

     TextView tvhighscore= (TextView) findViewById(R.id.highscore); 
     tvscore = (TextView) findViewById(R.id.score); 
     Button count = (Button) findViewById(R.id.button1); 
     //here you retrieve the value of the highscore 
     prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE); 
     int highscore = prefs.getInt("score", 0); 
     tvhighscore.setText(String.valueOf(highscore)); 



    } 

    public void onClick (View view) { 
     score++; 
     //here you save the value of the score in your pref 
     tvscore.setText(String.valueOf(score)); 
     Editor editor = prefs.edit(); 
     editor.putInt("score", score); 
     editor.commit(); 
    } 

} 

Незнайка, если это именно то, что вы искали, но это должно помочь вам понять логику :)

Удачи!

+0

Я попробую, спасибо! –

0

Я рекомендую вам создать класс для управления вашим sp. Я оставляю вам пример ниже.

public class SharedPrefsManager { 
    private static final String USER_CODE = "userCode"; 
    private static SharedPreferences sharedPreferences; 
    private static SharedPreferences.Editor prefEditor; 

    private static void setPreferences(Context context) { 
     if (context == null) { 
      context = Application.getContext(); 
     } 
     sharedPreferences = context.getSharedPreferences("APP_NAME", 0); 
    } 

    public static int getCodigoUsuario(Context context) { 
     setPreferences(context); 
     return sharedPreferences.getString(USER_CODE, 0); 
    } 

    public static void setCodigoUsuario(int userCode, Context context) { 
     setPreferences(context); 
     prefEditor = sharedPreferences.edit(); 
     prefEditor.putInt(USER_CODE, userCode); 
     prefEditor.commit(); 
    } 
    } 

СОХРАНИТЬ: SharedPrefsManager.setCodigoUsuario (13, контекст);

GET SharedPrefsManager.getCodigoUsuario (контекст);

+1

И с этим классом я сохраняю его, как я пытался это сделать? –

+0

SharedPrefsManager.setCodigoUsuario (пользователь, контекст); –

Смежные вопросы