Android SharedPreference无法正常工作

时间:2016-11-08 16:38:14

标签: android android-sharedpreferences

我正在尝试保存一个从EditText中获取的int,并且正如人们所说的最好使用SharedPreference,我听了,但每次我试图保存/加载时,程序都会崩溃!任何想法?

public static final String MY_PREFS_NAME = "MyPrefsFile";
String getsturdvalue;
int sturd;
EditText sturdadapter;
int sturdadaptercount;

public void onSave(View view) {
    SharedPreferences.Editor editor = (SharedPreferences.Editor) getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
    editor.putInt(getstrengthvalue, strnth);
    editor.apply();
}

public void onLoad(View view) {
    SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
    String restoredText= prefs.getString("text", null);
    if (restoredText != null) {
        int insertvalue = prefs.getInt("insertvalue", strnth);
        int adapter = prefs.getInt("adapter", strengthadaptercount);
    }
    strengthadapter.setText(prefs.getInt("" ,strengthadaptercount));
}

1 个答案:

答案 0 :(得分:0)

似乎是ClassCastException。试试这个:

public void onSave(View view) {
    SharedPreferences.Editor editor = (SharedPreferences.Editor)
        getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
    // ...
}