2013-04-03 118 views
-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)); 
    } 

我的logcat:商店的TextView从ArrayList中

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)); 

PLZ给我的解决方案

+0

什么是你的问题,请参见[问] – glh

回答

3

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

因为你的TextView为null,

你刚才宣布的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)); 
    } 
1
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的阵列,但在尚未初始化每个元素。

0

你必须做的,如:

for (int i = 0; i < al.size(); i++) { 
      tv[i] = new TextView(context); 
      tv[i].setText(al.get(i)); 
     } 
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 
    }