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,开发者_C百科 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);
}
The NullPointerException appears at this line:
prefsEditor.putInt(WEIGHT, Integer.parseInt(weightField.getText().toString()));
Thanks!
EDIT: Here's the activity that calls 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);
}
}
When the "next" button is pushed in main.xml, it sends next
which switches Activities from CalorieIntakeCalculator to Exercise.
Since you successfully used prefsEditor several times above that line, it seems like weightField must be null. Have you checked its value in the debugger?
EDIT: I also just noticed that you never assigned a value to WEIGHT, nor any of the other Strings for the SharedPreferences keys, so they are all null. You need to fix that.
String WEIGHT = "weight";
String AGE = "age";
String FEET = "feet";
String INCHES = "inches";
For the weight field, make sure there is an EditText in your exercise layout that has the id R.id.EditTextWeight
精彩评论