[英]Android (Java) Enum null pointer error
我四肢癱瘓,試圖在開關盒中使用枚舉。 但顯然,我做錯了。
這是我定義枚舉的代碼:
public class WorkoutStopwatch extends Activity implements OnClickListener {
private boolean timer_running = false;
public enum CounterState {
WORKOUT, REST
}
CounterState state;
以及我在其中使用的重寫的onClick方法:
@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.start_button:
timer_running = true;
// Make call to timer update class to start
break;
case R.id.stop_button:
timer_running = false;
// Make call to timer update class to stop
break;
case R.id.reset_button:
if (!timer_running) {
switch(state) {
case WORKOUT:
// TODO: Reset the counter to the workout time
break;
case REST:
// TODO: Reset the counter to the rest time
break;
}
}
break;
}
}
當我運行程序時,onClick調用“開始”和“停止”按鈕可以正常工作,但是“重置”按鈕導致應用程序崩潰,並出現“ FATAL EXCEPTION:main”和“ java.lang.NullPointerException”錯誤,指向開關的行。 從我一直在閱讀的內容來看,在讀取開關時,enum的值似乎為null,因此我將enum聲明更改為:
private enum CounterState {
UNKNOWN(0),
WORKOUT(1),
REST(2);
private int stateValue;
CounterState(int state) {
this.stateValue = state;
}
public int getStateValue() {
return stateValue;
}
public void setStateValue(int state) {
this.stateValue = state;
}
}
CounterState state;
我會同意的,看起來更完整,但仍然遇到問題。 留下這樣的代碼並不能解決問題,似乎在讀取時狀態為null。 像這樣在對象的聲明中添加一個int:
CounterState state(0);
給我一個Eclipse錯誤“令牌“ 0”上的語法錯誤,刪除此令牌”。 所以我有點迷路了。 據我所知,現在有一個枚舉的構造函數,我應該可以傳遞一個int值來初始化其創建時的值,但這似乎行不通。
在使用state
變量之前,您是否嘗試過初始化它?
CounterState state = CounterState.UNKNOWN;
空指針異常僅在您使用變量之前或未對其進行初始化時出現。 因此,首先檢查您在此處使用的所有變量及其初始化步驟。 自己做,所以將來您永遠不會犯這種錯誤。
您的錯誤原因可能是:
“ v.getId()”為空。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.