textText用于TextView数组的空指针

时间:2016-04-19 17:47:00

标签: android

我已经盯着这个看了大约一个小时,无法弄清楚为什么TextView为空。

我已经定义了它:

TextView[] tvEvidenceID;

初始化它:

int x = cursorEvidence.getCount();
tvEvidenceID = new TextView[x];


 do {
                    int i = 0;
                    tvEvidenceID[i].setId(i);
                    tvEvidenceID[i].setText("Evidence ID: " + cursorEvidence.getString(cursorEvidence.getColumnIndex("_id")));
                    tvEvidenceID[i].setPadding(50, 50, 0, 0);
                    tvEvidenceID[i].setTextColor(getColor(R.color.white));
                    linearLayout.addView(tvEvidenceID[i]);
                    i++;
    }
 while (cursorEvidence.moveToNext());

由以下原因引起的堆栈跟踪:

 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setId(int)' on a null object reference

1 个答案:

答案 0 :(得分:2)

您创建了数组,但没有创建数组中的对象。 只需添加do { int i = 0; tvEvidenceID[i] = new TextView(context); tvEvidenceID[i].setId(i); tvEvidenceID[i].setText("Evidence ID: " + cursorEvidence.getString(cursorEvidence.getColumnIndex("_id"))); tvEvidenceID[i].setPadding(50, 50, 0, 0); tvEvidenceID[i].setTextColor(getColor(R.color.white)); linearLayout.addView(tvEvidenceID[i]); i++; } while (cursorEvidence.moveToNext());

即可
   <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-jdk14</artifactId>
      <version>1.6.1</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-nop</artifactId>
      <version>1.6.0</version>
      <exclusions>
        <exclusion>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
        </exclusion>
      </exclusions>
    </dependency>