我的問題是雙桶,我正在開發一個簡單的測驗應用程序使用android studio。對我來說,代碼看起來不錯,編譯應用程序時沒有顯示錯誤消息。但是,當我運行應用程序時,問題(字符串)不會顯示在UI中,當我點擊提交答案按鈕時,應用程序就會崩潰。以下是我正在實施的代碼示例。任何幫助或建議將不勝感激。謝謝爲什麼我的Android Quiz應用程序在提交答案時崩潰並且不打印問題?
package com.example.shaun.quiz;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public int currentQuestion;
public String[] questions;
public String[] answers;
Button answerButton;
Button questionButton;
public TextView questionView;
public TextView answerView;
public EditText answerText;
public void main() {
questions = new String[]{"1+2= ?", "1+1= ?",}; /*Array of Hard Coded Questions*/
answers = new String[]{"3", "2",}; /*Array of Hard Coded Answers to indexed to match the questions*/
currentQuestion = -1; /*This will index the questions to be used*/
answerButton = (Button) findViewById(R.id.AnswerButton);
questionButton = (Button) findViewById(R.id.QuestionButton);
questionView = (TextView) findViewById(R.id.QuestionTextView);
answerView = (TextView) findViewById(R.id.AnswerTextView);
answerText = (EditText) findViewById(R.id.AnswerText);
answerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkAnswer();
}
});
questionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showQuestion();
}
});
}
public void showQuestion() {
currentQuestion++;
if (currentQuestion == questions.length)
currentQuestion = 0;
questionView.setText(questions[currentQuestion]);
questionView.setText("");
answerText.setText("");
}
public boolean isCorrect(String answer)
{
return (answer.equalsIgnoreCase(answers[currentQuestion]));
}
public void checkAnswer()
{
String answer = answerText.getText().toString();
if(isCorrect(answer))
answerView.setText("Correct!"); /*answerView, text view set to print the string in the event of the correct answer*/
else
answerView.setText("Sorry, the Correct answer is "+answers[currentQuestion]); /*answers[currentQuestion] answers reads the answer to the current question in use */
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
main();
}
}
歡迎,您可以添加此崩潰的堆棧跟蹤。這些非常有用 – AxelH
PS:在showQuestion中,您設置問題文本然後清除它(並且您不要在創建時調用該方法,只需單擊)。並刪除數組中的空單元格(最後一個',') – AxelH
刪除'questionView.setText(「」);'使您的問題可見。 –