2017-01-31 7 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); 

である。これは、これが私の最後の活動

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); 
} 

ある

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

私の第二の活動である

私のコードですキーA1とA2からの値。しかし、私が得たのは、私がそれらを合計するときの価値ではなく、鍵でした。

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); 

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

ザッツあなたは彼がSharedPrefrencesからこれらのキーの値を取得し、それらに私はこれを試してみた – Sanjeet

答えて

2

追加または変数に鍵を連結するので、それはあなたのSharedPreferencesの値に

+0

を追加する必要がありますが、私は、各キーから値を取得していない、結果は0 –

+0

あるあなたは試すなかったので、この行はsharedPreference SharedPreferencesにアクセスしている間です。pref = PreferenceManager.getDefaultSharedPreferences(this); ? – xFighter

+0

私はしましたが、まだ動作していません –

0

アクセスありがとうございます。そして、intを計算したいので、合計結果を浮動小数点型または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(); 
} 

を提出したとして

は、2つのキーを作る何かをすると、それは整数であるから、あなたは文字列の形式に結果をキャストする必要があります。

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

SharedPreference starting guide

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キーを4とA2で1にします。 –

+0

A1とA2を宣言したコードを表示できます –

+0

解決しました、ありがとう! –

関連する問題