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