用Java动态创建TextViews - NullPointerException

时间:2013-09-03 20:28:04

标签: java android nullpointerexception textview

我尝试在Java中添加一些TextViews。我假设当我想使用setText()方法时,我应该更早地将我的Java的TextView对象与XML的TextView连接 - 我使用setId()

最后,我在使用setId()的行中得到了NullPointerException。

我的代码:

TextView[] tvQuestion = new TextView[numberOfQuestions];
TextView[] tvAnswer1 = new TextView[numberOfQuestions];
TextView[] tvAnswer2 = new TextView[numberOfQuestions];
TextView[] tvAnswer3 = new TextView[numberOfQuestions];

LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);

for (int i = 0; i < numberOfQuestions; i++) {
    tvQuestion[i].setId(View.generateViewId()); // NullPointerException!
    tvAnswer1[i].setId(View.generateViewId());
    tvAnswer2[i].setId(View.generateViewId());
    tvAnswer3[i].setId(View.generateViewId());

    tvQuestion[i].setLayoutParams(params);
    tvAnswer1[i].setLayoutParams(params);
    tvAnswer2[i].setLayoutParams(params);
    tvAnswer3[i].setLayoutParams(params);

    tvQuestion[i].setText(question[i]);
    tvAnswer1[i].setText(option1[i]);
    tvAnswer2[i].setText(option2[i]);
    tvAnswer3[i].setText(option3[i]);

    layAll.addView(tvQuestion[i]);
    layAll.addView(tvAnswer1[i]);
    layAll.addView(tvAnswer2[i]);
    layAll.addView(tvAnswer3[i]);
}

编辑:

解决方案:Philipp Jahoda的职位。

1 个答案:

答案 0 :(得分:3)

您刚刚为TextViews创建了一个数组。 只要未初始化,Array中的TextViews为空

所以你需要打电话

tvQuestion[i] = new TextView(Context);
tvAnswer[i] = new TextView(Context);
// and so on ...

// and then later
tvQuestion[i].setId(View.generateViewId());
// and so on ...

在设置ID和其他内容之前。