2017-01-31 31 views
1

我想使用SharedPreferences中的密鑰計算2個值。 這是我的代碼如何使用SharedPreferences中的整數值計算密鑰

這是我的第一個活動

SharedPreferences.Editor editor = sharedpreferences.edit(); 
     editor.putInt(A1, option_scoreA1); 
     editor.commit(); 
     Intent intent = new Intent(QuestionActivity.this, SecondActivity.class); 
     startActivity(intent); 

這是我的第二個活動

SharedPreferences.Editor editor = sharedpreferences.edit(); 
      editor.putInt(A2, option_scoreA4); 
      editor.commit(); 
      Intent intent = new Intent(SecondActivity.this, TestFinalActivity.class); 
      startActivity(intent); 

這是我的最後一個活動

protected QuestionActivity activity1; 
protected SecondActivity activity2; 

String c = activity1.A1; 
String b = activity2.A2; 

String A = c + b ; 

@Bind(R.id.hasil) 
TextView hasil; 

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

public void total() { 
    hasil = (TextView) findViewById(R.id.hasil); 
    hasil.setText(A); 
} 

我想TOTALIZE各來自鍵A1和A2的值。但是我得到的是關鍵,而不是總結它們時的價值。

謝謝

+0

那是因爲你需要得到他從SharedPrefrences這些鍵的值,然後將它們添加 – Sanjeet

回答

2

這是因爲你添加或連接鍵爲可變一個。而你想計算整數,所以你最好把總結果放到float或int數據類型中,對嗎?

做一些如下圖所示

非常拳頭都讓兩個按鍵爲您的實例在QuestionActivity類

public static final String KEY_A = "ka"; 
public static final String KEY_B = "kb"; 


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

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); 

    int a = sharedPreferences.getInt(QuestionActivity.KEY_A, 0); 
    int b = sharedPreferences.getInt(QuestionActivity .KEY_B, 0); 
    A = a+b; 

    total(); 
} 

提交併因爲它是整數,則需要將結果轉換成字符串格式。

public void total() { 
    hasil = (TextView) findViewById(R.id.hasil); 
    hasil.setText(String.valueOf(A)); 
} 

SharedPreference starting guide

+0

我想這一點,但我沒有從每個鍵獲取值,結果爲0 –

+0

做嘗試此行訪問sharedPreference時的SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this); ? – xFighter

+0

我做了,但它仍然不能正常工作 –

0

獲得價值SharedPreferences

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); 

int value1 = preferences.getInt("your key", default_value); 
int value2 = preferences.getInt("your key", default_value); 
0

首先創建sharedpreferences然後拿到鑰匙的值。

SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this); 

int c = pref.getInt(A1, 0) // here A1 is the key and 0 is default value 
int b = pref.getInt(A2, 0) // here A2 is the key and 0 is default value 

int A = c + b; 
+0

我試過這個,但是我沒有得到每個鍵的值,結果是0.我用A1和A2填充A1鍵。 –

+0

你可以在你聲明A1和A2的地方顯示你的代碼 –

+0

它是解決了,謝謝! –

相關問題