2013-09-30 43 views
0

我想將此活動中的totalBalance保存到SharedPreferances並將其恢復到另一個類中。如何在SharedPeference中保存活動中的值並訪問所有其他類

,所以我想totalbalance被顯示在同一應用程序的另一個活動...... 如果可能的話也在其他activites編輯...

請幫助...謝謝

button1.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      // Do something in response to button click 

      // Genrating random number Random number 
      Random rn = new Random(); 
      randomNumber = (int) rn.nextInt(9) + 1; 

      // changes textView1 equals to random number 
      textView1.setText("Random Number is " 
        + Integer.toString(randomNumber)); 
      button1.setText("Play Again"); 

      // Matching random number to ArrayList 
      if (positive_IDs.contains(randomNumber)) { 
       // if matched then changes textView2 to Matched Number 
       textView2.setText("Number: " 
         + Integer.toString(randomNumber) + " Matched"); 

       totalBalance = totalBalance + winingPrize; 
       textView5.setText("Total Balance = Rs: " 
         + String.format("%.2f", totalBalance)); 



      } 

     } 

回答

4

試對此,

public void saveValue(String lock, Context context) { 
    Editor editor = context 
      .getSharedPreferences(KEY, Activity.MODE_PRIVATE).edit(); 
    editor.putString("Value", lock); 
    editor.commit(); 
} 

public String getValue(Context context) { 
    SharedPreferences savedvalue = context.getSharedPreferences(KEY, 
      Activity.MODE_PRIVATE); 
    return savedvalue.getString("Value", ""); 

} 
+0

你getYourValue是有缺陷的,它總是分鐘的價值。 – RvdK

+1

@RvdK現在我編輯了 –

4

保存價值如下

int Value; 
    private void saveValues(){ 
    SharedPreferences readSP = getSharedPreferences("String", MODE_PRIVATE); 
      SharedPreferences.Editor editor = readSP.edit(); 
      editor.putString("String", Value); 
      editor.commit(); 
    } 

您的任何類Retrive值作爲繼

int value; 


private void getSavedValue() 
{ 
SharedPreferences settings = getSharedPreferences("String", MODE_PRIVATE); 
value=settings.getString("String", ""); 
} 
1

使用下面的代碼以檢索從SharedPreference你的價值,你想以檢索總餘額的價值在其他類寫這個

SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(YourActivityName.this); 

Editor edit1 = remembermepref.edit(); 
      edit1.putInt("totalbalance_key",totalBalance); 
      edit1.commit(); 

並將總餘額存儲到您的活動中使用的ShardPreference中:

SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(YourActivityName.this); 
int totalbalance = pref.getInt("totalbalance_key"); 

現在使用你想要的totalbalance方式。 最重要的事情是檢查你是否使用相同的密鑰恢復以及tostore在SharedPreference

值希望這有助於..

1
// try this 
SharedPreferences sharedPreferences = getSharedPreferences("yourSharePreferenceName", MODE_PRIVATE); 
SharedPreferences.Editor editor = sharedPreferences.edit(); 
editor.putBoolean("balance", String.format("%.2f", totalBalance)); 
editor.commit(); 

SharedPreferences sharedPreferences = getSharedPreferences("yourSharePreferenceName", MODE_PRIVATE); 
String total = sharedPreferences.getString("balance"); 
相關問題