我對Android開發非常陌生,我對NullPointerException
有個疑問。當從第一個活動頁面按下按鈕時,它將切換到第二個活動,其中有一個NullPointerException
。 下面是main.xml中「下一個」按鈕(這是按壓以切換活動的那一個)的代碼:更改活動時出現NullPointerException
<Button
android:id="@+id/ButtonNext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/next"
android:onClick="next">
</Button>
下面是所述第一活動的代碼:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
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);
}
}
當「下一個」按鈕,它切換到練習活動:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class Exercise extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.exercise);
final EditText weightField = (EditText) findViewById(R.id.EditTextWeight);
try {
((Global) this.getApplication()).setWeight(Integer.parseInt(weightField.getText().toString()));
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
在練習課,我將ContentView設置爲exercise.xml。 在接下來的幾條語句中,我想將全局整數權重設置爲用戶放入EditTextWeight EditText框中的數字。 這裏是在Global.java文件,它擴展Appllication代碼,使全局變量:
import android.app.Application;
public class Global extends Application {
private int weight;
private int age;
private int feet;
private int inches;
//START WEIGHT
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
//END WEIGHT
//START AGE
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//END AGE
//START FEET
public int getFeet() {
return feet;
}
public void setFeet(int feet) {
this.feet = feet;
}
//END FEET
//START INCHES
public int getInches() {
return inches;
}
public void setInches(int inches) {
this.inches = inches;
}
//END INCHES
}
當我嘗試,並在模擬器中運行的程序,該程序崩潰。我看着在logcat中,發現NullPointerException
使用斷點在此行中exercise.java:
((Global) this.getApplication()).setWeight(Integer.parseInt(weightField.getText().toString()));
謝謝〜:)
非常感謝!它似乎會對我有用:) 不幸的是,我可能不得不重新編寫所有的代碼大聲笑。但是,我會研究它:D – koysean 2011-03-13 20:04:34