private void SavePreferences(){
try
{
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
myScore = ((TextView)findViewById(R.id.score)).getText().toString();
myWord = ((TextView)findViewById(R.id.word)).getText().toString();
editor.putString("saveScore", myScore.toString());
editor.putString("saveWord", myWord.toString());
editor.commit();
}
catch (Exception e) {
System.err.println("scoreText or wordView are null " + e.getMessage());
}
}
private void LoadPreferences(){
try {
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
myScore = ((TextView)findViewById(R.id.score)).getText().toString();
myWord = ((TextView)findViewById(R.id.word)).getText().toString();
scoreText.setText(sharedPreferences.getString("saveScore", myScore.toString()));
wordView.setText(sharedPreferences.getString("saveWord", myWord.toString()));
}
catch (Exception e) {
System.err.println("scoreText or wordView are null " + e.getMessage());
}
}
scoretext和wordView並沒有從myScore和myWord中分配值,儘管在調試時它們有一個值。加載首選項空值
調試結果:
myScore:"990" scoreText :null
wordView: null myWord"_ _ a _ _"
編輯:
凡savePrefernces被稱爲:
@Override
public void onBackPressed() {
SavePreferences();
super.onBackPressed();
}
當負載首叫做:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_avtivity);
LoadPreferences();
}
的loadPrefernces被在onBackPressed中調用以檢查myScore或myWord是否爲null。
當從onCreate調用加載首選項時,正在調用異常!
錯誤消息:
該消息被稱爲第一時間,其中的值仍然爲空(異常被預期)以及第二時間時的值不能爲空(未預期的異常)
05-13 17:23:06.671 31547-31547/mt.edu.mcast.guesstheword2 W/System.err:scoreText或wordView是null嘗試調用虛函數 方法'void android.widget.TextView.setText( java.lang.CharSequence)' on null object reference
您的loadPreferences和savePreferences函數是否從同一活動調用? – Elye
爲了能夠調試我做了兩個方法onBackPressed(檢查myScore和myWord是否有值)。 LoadPrefernces應該在onCreate上實現,但是當插入到onCreate時它會進入異常(scoreText或wordView爲空)。 – NOSMILE
從相同的onPackPressed函數調用?你能顯示功能代碼嗎? – Elye