试图在游戏中保存得分。你如何阅读SharedPreferences?

时间:2016-09-29 01:23:02

标签: android

我想在游戏中保存一个分数。我使用了SharedPreferences(第13-16行)来保存分数(我认为)。我想知道如何在用户离开应用程序时阅读SharedPreferences并保留它。任何帮助表示赞赏。

public class MainActivity extends Activity implements OnClickListener{

TextView textView1;
EditText editText1;
Button button1;
int counter = 0;

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    setContentView(R.layout.main);}

protected void onStop()
{
    super.onStop();
    SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putInt("key", counter);
    editor.commit();}


protected void onResume()
{
    super.onResume();
    SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
    int defaultValue = 0;
    int counter = prefs.getInt("key", defaultValue);


    textView1 = (TextView)findViewById(R.id.textView1);
    editText1 = (EditText)findViewById(R.id.editText1);
    button1 = (Button)findViewById(R.id.button1);
    button1.setOnClickListener(this);}

public void onClick(View v){
    if (v == button1){
        counter++;
        editText1.setText(Integer.toString(counter));}}}

2 个答案:

答案 0 :(得分:1)

您应该在 onCreate 中加载SharedPreferences,并将其保存在 onPause onStop onDestory 中。

Look at this

答案 1 :(得分:1)

正如@ n​​jzk2所说,你可以从Saving Key-Value Sets阅读。

这样的事情:

SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
int defaultValue = 0; // default value for your counter.
int counter = prefs.getInt("key", defaultValue);