Android商店得分并保存在应用程序上

时间:2014-08-07 13:27:46

标签: android android-intent int sharedpreferences

我希望能够从不同的活动中获得多个意图并将其存储在应用程序状态中。

Intent intent = getIntent();
int score1 = intent.getIntExtra("comp", 0);

Intent intent2 = getIntent();
int score2 = intent2.getIntExtra("comp2", 0);

int score = score1 + score2;

//setting preferences
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("key", score);
editor.commit();

并从SharedPreferences获取数据:

SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
int scoretotal = prefs.getInt("key", 0); //0 is the default value
s1.setText("Score: " + scoretotal);

但是这只存储了第一个或第二个意图,当应用程序关闭时,值也会返回0。我希望应用程序存储这两个值并永久保留在应用程序上,直到卸载该应用程序。

2 个答案:

答案 0 :(得分:0)

如果我理解你的话,那就是你需要做的**multiple intents** from **different activities** and store it in on the application state

活动A

Intent intent = getIntent();
int score1 = intent.getIntExtra("comp", 0);
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", 
                            Context.MODE_PRIVATE);

// Get the 2nd Score from shared preference
int score2= prefs.getInt("comp2", 0); //0 is the default value


 // Sum both the scores so that the value in Activity A is updated:
 int score = score1 + score2;

 // Save score1 and total score in shared preference
 SharedPreferences.Editor editor = prefs.edit();
 editor.putInt("comp", score1 );
 editor.putInt("key", score);
 editor.commit();

活动B

 Intent intent2 = getIntent();
 int score2 = intent2.getIntExtra("comp2", 0);
 SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", 
                            Context.MODE_PRIVATE);

 // Get the 1st Score from shared preference
 int score1= prefs.getInt("comp", 0); //0 is the default value

 // Sum both the scores so that the value in Activity B is updated:
 int score = score1 + score2;

 // Save score1 and total score in shared preference
 SharedPreferences.Editor editor = prefs.edit();
 editor.putInt("comp2", score2 );
 editor.putInt("key", score);
 editor.commit();

答案 1 :(得分:-2)

你为什么不这样做? :

Intent intent = getIntent();
    int score1 = intent.getIntExtra("comp", 0);
    int score2 = intent.getIntExtra("comp2", 0);

    int score = score1 + score2;
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putInt("key", score);
    editor.commit();