-2
ArrayList<String> al = new ArrayList<String>();
    Cursor c = database.query("remedies", new String[] { "remedy" },
            "d_id=?", new String[] { "" + index }, null, null, null);
    while (c.moveToNext()) {
        al.add(c.getString(0));
    }
    c.close();

    TextView[] tv = new TextView[al.size()];
    for (int i = 0; i < al.size(); i++) {
        tv[i].setText(al.get(i));
    }

我的日志猫:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ayurvedicapp/com.example.ayurvedichomecure.Remedies}:
java.lang.NullPointerException

Exception at: tv[i].setText(al.get(i));

请给我解决方案

4

4 回答 4

3

tv[i].setText(al.get(i));这导致异常。

因为您的 TextView 为空,

您刚刚声明了一个 TextView 数组,但还没有真正实例化 textview。

试试这个

TextView[] tv = new TextView[al.size()];
    for (int i = 0; i < al.size(); i++) {
       tv[i]=new TextView(context);
        tv[i].setText(al.get(i));
    }
于 2013-04-03T11:18:42.780 回答
2
for (int i = 0; i < al.size(); i++) {
    tv[i] = new TextView(context); // Provide a proper context or if you plan to use findViewById
    tv[i].setText(al.get(i));
}

您刚刚声明了 TextView 数组,但还没有初始化其中的每个元素。

于 2013-04-03T11:19:41.347 回答
0

你必须这样做:

for (int i = 0; i < al.size(); i++) {
            tv[i] = new TextView(context);
            tv[i].setText(al.get(i));
        }
于 2013-04-03T11:21:56.920 回答
0

您可以使用以下代码

 TextView[] tv = new TextView[al.size()]; //Textviews of the arraylist size. array of textviews with 
 for (int i = 0; i < al.size(); i++) { //loop to the size of the list
  tv[i] = new TextView(MainActivity.this); //new textview 
  tv[i].setText(al.get(i)); //set textview with the data from the list using index i
  }
于 2013-04-03T11:25:01.260 回答