2016-11-08 63 views
0

我試圖保存一個int,我從EditText中獲得,並且正如人們所說的那樣,最適合使用SharedPreference,我傾聽了,但是每次我嘗試保存/加載時,程序崩潰!有任何想法嗎?Android 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)); 
} 
+0

試試這個:http://stackoverflow.com/questions/23024831/android-shared-preferences-example –

+0

被getsturdvalue初始化爲任意值? –

+0

使用commite()並檢查它的返回值(boolean)它是否爲commit? – Onkar

回答

0

它似乎是ClassCastException。試試這個:

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