零参数构造函数。为什么和在哪里?

时间:2015-02-02 16:17:09

标签: java android

我有一个构造函数:

public class Question {



String question;
boolean correctAnswer;


public Question(String question, boolean correctAnswer)
{
    this.question = question;
    this.correctAnswer = correctAnswer;
}

}

在mainActivity中我想显示问题,但是我得到零参数构造函数错误:

public class MainActivity extends ActionBarActivity {

Button mYes;
Button mNo;
TextView mQuestion;




@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mYes = (Button)findViewById(R.id.button2);
    mNo = (Button)findViewById(R.id.button);
    mQuestion = (TextView)findViewById(R.id.textView);
    //question list
    ArrayList<Question> questions = new ArrayList<>();
    //adding question
    questions.add(first);
    //show the question.
    mQuestion.setText((CharSequence) questions.get(0));


}
//Creating question
Question first = new Question("Do i understand this code?", false);

我知道我必须在某处创建某种空构造函数。 http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html可能会回答我的问题,但我不是英语最好的,我只是无法理解如何实现我需要的代码。

2 个答案:

答案 0 :(得分:0)

questions.get(0)返回Question类型的对象。您无法将其转换为CharSequence

更改此

mQuestion.setText((CharSequence) questions.get(0));

mQuestion.setText(questions.get(0).question);

注意如果Question类与MainActivity在同一个包中,则要么Question属性为public,要么为它们创建getter方法

还要确保使用此代码

Question first = new Question("Do i understand this code?", false);
questions.add(first);中使用

之前,您将在NullPointerException

中获得mQuestion.setText(questions.get(0).question);

答案 1 :(得分:-1)

Bisides Rohit5k2所写的内容。

这是java。然后你首先创建de对象,然后你可以调用它。根据你的代码,在方法onCreate上不会退出首先调用的对象,因为这是从onCreate方法创建的:

@Override
protected void onCreate(Bundle savedInstanceState) {
...
//Creating question
Question first = new Question("Do i understand this code?", false);
//question list
ArrayList<Question> questions = new ArrayList<>();
//adding question
questions.add(first);
//show the question.
mQuestion.setText((CharSequence) questions.get(0).getQuestion());

其中,getQuestion()是问题类的方法:

public String getQuestion() {
    return this.question;
}