2013-04-03 89 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 
    }