2015-04-29 53 views
0

我想將sqlite列拆分爲數組,然後爲數組中的每個項目添加TextView。下面是我的功能在陣列添加TextView每個項目:爲陣列中的每個項目添加TextView

private void BuildTable() { 

    sqlcon.open(); 
    Cursor c = sqlcon.readEntry(); 

    int rows = c.getCount(); 
    int cols = c.getColumnCount(); 
    String[] array; 
    c.moveToFirst(); 

    // outer for loop 
    for (int i = 0; i < rows; i++) { 

     TableRow row = new TableRow(this); 
     row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 
       LayoutParams.WRAP_CONTENT)); 

     // inner for loop 
     for (int j = 0; j < cols; j++) { 

      TextView tv = new TextView(this); 
      tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, 
        LayoutParams.WRAP_CONTENT)); 
     // tv.setBackgroundResource(R.drawable.cell_shape); 
      tv.setGravity(Gravity.CENTER); 
      tv.setTextSize(18); 
      tv.setPadding(0, 5, 0, 5); 
      array = c.getString(1).split(","); 
      for (int k = 0; k < array.length; k++) { 
       tv.setText(array[k]); 
       row.addView(tv); 

      } 

     } 

     c.moveToNext(); 

     table_layout.addView(row); 

    } 
    sqlcon.close(); 
} 

我收到以下錯誤:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.logquiz.thequiz.logquiz/com.logquiz.thequiz.logquiz.RulesActivity}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

+0

爲什麼不只是使用'ListView'? –

回答

0

問題是在內部進行循環

for (int k = 0; k < array.length; k++) { 
     tv.setText(array[k]); 
     row.addView(tv); 
} 

這裏您將相同的行實例添加相同的TextView倍數,這是不允許的。更改像

for (int k = 0; k < array.length; k++) { 
     tv.append(array[k]); 
} 
row.addView(tv); 

代碼這樣每個TextView的是最多一次當前行

0

我猜正確的溶液是甚至有點更激烈的比黑帶建議。下面的代碼片段實際上是文本的每一行創建一個新的TextView:

// inner for loop 
    for (int j = 0; j < cols; j++) { 

     array = c.getString(1).split(","); 
     for (int k = 0; k < array.length; k++) { 
     TextView tv = new TextView(this); 
     tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, 
       LayoutParams.WRAP_CONTENT)); 
    // tv.setBackgroundResource(R.drawable.cell_shape); 
     tv.setGravity(Gravity.CENTER); 
     tv.setTextSize(18); 
     tv.setPadding(0, 5, 0, 5); 
     tv.setText(array[k]); 
     row.addView(tv); 

     } 
    } 

問題是由黑帶正確識別:您要重複使用相同的TextView,而不是每次都創建一個新的。

相關問題