使用共享首选项在活动之间传递整数

时间:2014-05-18 06:58:09

标签: android

我试图将此SCORE整数从一个活动传递到另一个活动。我在共享偏好方面遇到了困难。在MainActivity中我没有收到任何警告或错误但在ScoreActivity中我收到一条错误,说明方法getInt(String,int)在共享首选项类型中不适用于参数(long,int)。我该如何解决这个问题?

MainActivity

private int SCORE = 0;


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

    SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putInt("SCORE", SCORE);
    editor.commit();

ScoreActivity

private int SCORE = 0;

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


    SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
    int defaultValue = getResources().getInteger(SCORE);
    long SCORE = sharedPref.getInt(SCORE, defaultValue);

1 个答案:

答案 0 :(得分:1)

long SCORE = sharedPref.getInt(SCORE, defaultValue); // in your case SCORE is a int 

应该是

int SCORE = sharedPref.getInt("SCORE", defaultValue); 
//"SCORE" is the key
// return's a int value not long

检查文档

public abstract int getInt (String key, int defValue)

Added in API level 1
Retrieve an int value from the preferences.

Parameters
key The name of the preference to retrieve.
defValue    Value to return if this preference does not exist.
Returns
Returns the preference value if it exists, or defValue. Throws ClassCastException if there is a preference with this name that is not an int.
Throws
ClassCastException