使用SharedPreferences的NullPointerException

时间:2011-04-04 02:25:06

标签: android nullpointerexception sharedpreferences


我的代码在这里遇到问题。我在我的代码中使用SharedPreferences,并且我在代码中的一行获得了NullPointerException。这是完整的代码:

    public class Exercise extends Activity {
String WEIGHT = "0";
String AGE = "0";
String FEET = "0";
String INCHES = "0";

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.exercise);

    SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
    SharedPreferences.Editor prefsEditor = myPrefs.edit();
    prefsEditor.putInt(WEIGHT, 0);
    prefsEditor.putInt(AGE, 0);
    prefsEditor.putInt(FEET, 0);
    prefsEditor.putInt(INCHES, 0);
    prefsEditor.commit();


    final EditText weightField = (EditText) findViewById(R.id.EditTextWeight);
    try {
        prefsEditor.putInt(WEIGHT, Integer.parseInt(weightField.getText().toString()));
        prefsEditor.commit();
    } catch(NumberFormatException nfe) {
        System.out.println("Could not parse " + nfe);
    }   

NullPointerException出现在这一行:

prefsEditor.putInt(WEIGHT, Integer.parseInt(weightField.getText().toString()));

谢谢!

编辑:这是调用setContentView(R.layout.main)的活动:

public class CalorieIntakeCalculator extends Activity {
/** Called when the activity is first created. */


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

}

public void next(View view) {
    Intent intentExercise = new Intent(view.getContext(), Exercise.class);
    startActivityForResult(intentExercise, 0);
} 
}

当在main.xml中按下“next”按钮时,它会发送next,将活动从CalorieIntakeCalculator切换为Exercise。

1 个答案:

答案 0 :(得分:1)

由于您在该行上方多次成功使用了prefsEditor,因此看起来weightField必须为null。你在调试器中检查了它的值吗?

编辑:我还注意到你从未为WEIGHT指定值,也没有为SharedPreferences键指定任何其他字符串,因此它们都为空。你需要解决这个问题。

String WEIGHT = "weight";
String AGE = "age";
String FEET = "feet";
String INCHES = "inches";

对于权重字段,请确保练习布局中有一个具有ID为R.id.EditTextWeight

的EditText