我正在製作一個Sudoku應用程序,並且我想添加一個移動計數器,因此每當用戶輸入一個數字時,我都會看到一個與movecount一起顯示的textView當調用OnClick函數時textView setText()和append()崩潰
public class NumberButton extends Button implements OnClickListener {
private int number;
TextView moveCountText;
private int moves;
private String message;
public NumberButton(Context context, AttributeSet attrs) {
super(context, attrs);
setOnClickListener(this);
moveCountText = (TextView)findViewById(R.id.moveCountView);
}
@Override
public void onClick(View v){
moves++;
message="Move Count: "+ moves;
moveCountText.setText(message);
moveCountText.invalidate();
GameEngine.getInstance().setNumber(number);
}
public void setNumber(int number){
this.number = number;
}
}
問題是,setText說視圖是空的(空對象),但我不知道爲什麼。這是textView XML。
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Move count: 0"
android:id="@+id/moveCountView"
android:layout_marginLeft="100dp"
android:layout_marginStart="114dp"
android:layout_marginTop="450dp"/>
同樣正在發生的事情對我的勝利活動中,錯誤的是,其意圖是一個空對象
public void checkGame(){
int [][] sudGrid = new int[9][9];
for(int x = 0 ; x < 8 ; x++){
for(int y = 0 ; y < 8 ; y++){
sudGrid[x][y] = getItem(x,y).getValue();
}
}
if(SudokuChecker.getInstance().checkSudoku(sudGrid)){
Toast.makeText(context, "Congratulations!", Toast.LENGTH_LONG).show();
// opens victory screen
Intent nextScreen = new Intent(getApplicationContext(), VictoryActivity.class);
startActivity(nextScreen);
}
}
以下是錯誤消息
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at sudoku.view.buttonsgrid.NumberButton.onClick(NumberButton.java:33)
at android.view.View.performClick(View.java:5156)
at android.view.View$PerformClick.run(View.java:20755)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5832)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
和XML
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Move count: 0"
android:id="@+id/moveCountView"
android:layout_marginLeft="100dp"
android:layout_marginStart="114dp"
android:layout_marginTop="450dp"/>
有什麼異常的消息? – m02ph3u5
當你問問題時,請發佈你的堆棧跟蹤。 –
@ m02ph3u5新增錯誤訊息 –