java - 在 Java 中动态创建的 TextView - NullPointerException

标签 java android nullpointerexception textview

我尝试在 Java 中动态添加一些 TextView。我假设当我想使用 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 的帖子。

最佳答案

您刚刚为 TextView 创建了一个数组。 Array 中的 TextViews 为 null 只要它们没有被初始化。

所以你需要调用

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 和其他内容之前。

关于java - 在 Java 中动态创建的 TextView - NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18600915/

相关文章:

java - 应用程序引擎上的 slf4j AccessControlException

java - 嵌入式Jetty + ShiroFilter问题

java - 类方法检查它自己的成员不为空?

Java:如何计算程序的时间复杂度?

java - 在开发网络客户端应用程序时,你能推荐开发集成工具吗?

java - 将文件写入内部存储时崩溃

Android Studio 在运行 Flutter App 时抛出异常

android - 如何在android中以编程方式为 View 设置动画?

java - Vector 上的增强 for 循环中的空指针异常

java - Vector3f 还是 Vector3d?