Java 使用SharedReferences存储和检索int

Java 使用SharedReferences存储和检索int,java,android,variables,sharedpreferences,Java,Android,Variables,Sharedpreferences,这让我快发疯了。似乎根本无法让这一切起作用。我很没经验,所以任何小费都很重要。我希望这只是一个愚蠢的错误,有人可以解释 在一个类中派生一个数字。然后在该类中使用该数字,不会出现问题。在该类中,我使用共享首选项方法存储该数字。然而,在以后的一节课中,当我试图检索那个数字时,应用程序崩溃了 这是我处理并尝试存储数字的类: public class Summary extends Activity { @Override protected void onCreate(Bundle savedIn

这让我快发疯了。似乎根本无法让这一切起作用。我很没经验,所以任何小费都很重要。我希望这只是一个愚蠢的错误,有人可以解释

在一个类中派生一个数字。然后在该类中使用该数字,不会出现问题。在该类中,我使用共享首选项方法存储该数字。然而,在以后的一节课中,当我试图检索那个数字时,应用程序崩溃了

这是我处理并尝试存储数字的类:

public class Summary extends Activity {


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

        int Time = gotTime();

        // Create object of SharedPreferences.
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(Summary.this);
        //now get Editor
        SharedPreferences.Editor editor = sharedPref.edit();
        //put your value
        editor.putInt("TargetTime", Time);
        //commits your edits
        editor.

// I then display the Time on that screen which all works ok
        TextView textViewT = (TextView) findViewById(R.id.textView4);
        textViewT.setText("Time is " + Time); 

};


    public int gotTime(){

//do stuff to generate the value for time stored as variable PenileTim   

    return PenileTim;

};
}
然后在以后的课程中,我尝试检索时间:

public class Map extends Activity {

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


        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
        int VarTime = sharedPref.getInt("TargetTime", (Integer) null);

            TextView textViewP = (TextView) findViewById(R.id.textTest);
        textViewP.setText(" " + VarTime );

        }
 }

有人知道出了什么问题吗?

请详细说明这次事故。提供你的日志。在你的第一节课上,应该是编辑。beeditor.commit()?使用
getDefaultSharedReferences()
时必须小心。像这样使用应用程序上下文:
getDefaultSharedReferences(getApplicationContext())。不要使用putInt()/getInt()。而是转换为字符串并使用putString()/getString()。我从来没有得到第一对也工作。我把它转换成一个字符串,它工作得很好。