2015-10-10 3 views
0
<?xml version="1.0" encoding="utf-8"?> 
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/tbl_att_summary" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:stretchColumns="1" 
    android:shrinkColumns="1"> 
    <TableRow android:layout_marginTop="10dp" 
     android:layout_marginRight="2dp" 
     android:layout_marginBottom="-5dp" 
     android:layout_gravity="center_horizontal"> 
     <TextView 
      android:text="Class" 
      android:paddingLeft="10dip" /> 

     <TextView 
      android:text="Subject" 
      android:gravity="center_horizontal" /> 
     <TextView 
      android:text="Time Period" 
      android:layout_gravity="center_horizontal|bottom" 
      android:gravity="center_horizontal" 
      android:layout_marginRight="10dp" /> 
     <TextView 
      android:text="Work Days" 
      android:layout_marginRight="15dp" /> 
    </TableRow> 

    <TableRow android:layout_marginTop="5dp" 
     android:id="@+id/header_row_att_summary"> 
     <!-- first column for Class - Section --> 
     <TextView 
      android:layout_column="0" 
      android:id="@+id/txt_class_sec_att_summary" 
      android:textColor="@color/black" 
      android:textSize="20sp" 
      android:paddingLeft="10dp" /> 
     <!-- Second column for subject --> 
     <TextView 
      android:layout_column="1" 
      android:id="@+id/txt_subjec_att_summary" 
      android:text="Chemistry" 
      android:textSize="20sp" 
      android:paddingRight="10dp" 
      android:layout_marginRight="5dp" 
      android:textColor="@color/black" 
      android:layout_gravity="center_horizontal" 
      android:layout_marginLeft="5dp" /> 
     <!-- third column for duration (time period) for the attendance --> 
     <TextView 
      android:id="@+id/txt_time_period_att_summary" 
      android:text="Feb-15" 
      android:textColor="@color/black" 
      android:textSize="20sp" 
      android:gravity="fill_horizontal|end" 
      android:paddingRight="10dp" 
      android:layout_marginRight="5dp" 
      android:layout_gravity="center_horizontal" /> 
     <!-- fourth column for the total number of working days --> 
     <TextView 
      android:id="@+id/txt_working_days_att_summary" 
      android:text="18" 
      android:textColor="@color/black" 
      android:textSize="20sp" 
      android:gravity="fill_horizontal|end" 
      android:paddingRight="10dp" 
      android:layout_marginLeft="10dp" 
      android:layout_gravity="center_horizontal" 
      android:layout_marginRight="10dp" /> 
    </TableRow> 
    <View 
     android:layout_height="2dip" 
     android:background="#FF909090"/> 
    <TableRow 
     android:layout_marginTop="5dp"> 
     <TextView 
      android:background="@drawable/cell_shape" 
      android:layout_column="0" 
      android:paddingLeft="5dp" 
      android:text="Roll No" 
      android:layout_weight="0.2" 
      android:textStyle="bold" /> 

     <TextView 
      android:background="@drawable/cell_shape" 
      android:paddingLeft="5dp" 
      android:text="Name" 
      android:textStyle="bold" /> 
     <TextView 
      android:background="@drawable/cell_shape" 
      android:paddingLeft="5dp" 
      android:text="Days Present" 
      android:textStyle="bold" /> 
     <TextView 
      android:background="@drawable/cell_shape" 
      android:paddingLeft="5dp" 
      android:text="Percentage" 
      android:textStyle="bold" /> 

    </TableRow> 
    <TableRow 
     android:id="@+id/row_att_detail" 
     android:layout_marginTop="0dp"> 
     <TextView 
      android:id="@+id/txt_roll_no" 
      android:background="@drawable/cell_shape" 
      android:paddingLeft="5dp" /> 

     <TextView 
      android:id="@+id/txt_student_name" 
      android:background="@drawable/cell_shape" 
      android:paddingLeft="5dp" /> 
     <TextView 
      android:id="@+id/txt_days_present" 
      android:background="@drawable/cell_shape" 
      android:paddingLeft="5dp"/> 
     <TextView 
      android:id="@+id/txt_percentage" 
      android:background="@drawable/cell_shape" 
      android:paddingLeft="5dp"/> 

    </TableRow> 
</TableLayout> 

Соответствующий код JavaAndroid TableLayout Исключение при добавлении строки во время выполнения

public class ShowAttendanceSummary extends AppCompatActivity { 

     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_show_attendance_summary); 

      // set up the header rows 
      TableRow header_row = (TableRow) findViewById(R.id.header_row_att_summary); 
      ((TextView) header_row.findViewById(R.id.txt_class_sec_att_summary)). 
        setText((getIntent().getStringExtra("class") + "-" + 
          getIntent().getStringExtra("section"))); 
      ((TextView) header_row.findViewById(R.id.txt_subjec_att_summary)). 
        setText((getIntent().getStringExtra("subject"))); 

      // showing month/year is slightly tricky. As we are passing strings like "current year", 
      // "last year", or "till date", we need get the year value 
      Integer yr = Calendar.getInstance().get(Calendar.YEAR); 
      System.out.print("year=" + Integer.toString(yr)); 
      //Toast.makeText(getApplicationContext(), Integer.toString(yr), Toast.LENGTH_SHORT).show(); 
      switch (getIntent().getStringExtra("year")) { 
       case "current_year": 
        ((TextView) header_row.findViewById(R.id.txt_time_period_att_summary)). 
          setText((getIntent().getStringExtra("month") + "-" + 
            Integer.toString(yr))); 
        break; 
       case "last_year": 
        ((TextView) header_row.findViewById(R.id.txt_time_period_att_summary)). 
          setText((getIntent().getStringExtra("month") + "-" + 
            Integer.toString(yr - 1))); 
        break; 
       case "till_date": 
        ((TextView) header_row.findViewById(R.id.txt_time_period_att_summary)). 
          setText("Till Date"); 
        break; 
      } 

      final TableLayout tableLayout = (TableLayout) findViewById(R.id.tbl_att_summary); 
      final ArrayList<TableRow> tableRows = new ArrayList<>(); 

      // get the list of students 
      String tag = "AttendanceListSummary"; 
      final String student_list_url = "http://" + 
        MiscFunctions.getInstance().getServerIP(getApplicationContext()) 
        + "/student/list/" + 
        getIntent().getStringExtra("class") + "/" + 
        getIntent().getStringExtra("section") + "/?format=json"; 
      JsonArrayRequest jsonArrayRequest = new JsonArrayRequest 
        (Request.Method.GET, student_list_url, null, new Response.Listener<JSONArray>() { 
         @Override 
         public void onResponse(JSONArray response) { 
          for (int i = 0; i < response.length(); i++) 
           try { 
            JSONObject jo = response.getJSONObject(i); 
            // get the name of the student. We need to join first and last names 
            String f_name = jo.getString("fist_name"); 
            String l_name = jo.getString("last_name"); 
            String full_name = f_name + " " + l_name; 

            // get the roll number of the student 
            String roll_no = jo.getString("roll_number"); 
            TableRow detail_row = (TableRow) findViewById(R.id.row_att_detail); 
            ((TextView) detail_row.findViewById(R.id.txt_roll_no)). 
              setText(roll_no); 
            ((TextView) detail_row.findViewById(R.id.txt_student_name)). 
              setText(full_name); 
            tableRows.add(detail_row); 
            tableLayout.addView(tableRows.get(i)); 

           } catch (JSONException je) { 
            System.out.println("Ran into JSON exception " + 
              "while trying to fetch the list of students"); 
            je.printStackTrace(); 
           } catch (Exception e) { 
            System.out.println("Caught General exception " + 
              "while trying to fetch the list of students"); 
            e.printStackTrace(); 
           } 
         } 
        }, new Response.ErrorListener() { 
         @Override 
         public void onErrorResponse(VolleyError error) { 
          System.out.println("inside volley error handler"); 
          // TODO Auto-generated method stub 
         } 
        }); 

      com.classup.AppController.getInstance().addToRequestQueue(jsonArrayRequest, tag); 

      JSONObject params = new JSONObject(); 
      try { 
       params.put("class", getIntent().getStringExtra("class")); 
       params.put("section", getIntent().getStringExtra("section")); 
       params.put("subject", getIntent().getStringExtra("subject")); 
       params.put("month", getIntent().getStringExtra("month")); 
       params.put("year", getIntent().getStringExtra("year")); 
      } catch (JSONException je) { 
       System.out.println("unable to create json for selected subjects"); 
       je.printStackTrace(); 
      } 
     } 
    } 

Как можно видеть, что я пытаюсь добавить строки в моей TableLayout во время выполнения. Тем не менее, я получаю следующее исключение:

classup W/System.err: java.lang.IllegalStateException: Указанный ребенок уже имеет родителя. Сначала вы должны вызвать removeView() для родителя ребенка .

Может кто-нибудь взглянуть и предложить, какую ошибку я здесь делаю.

ответ

0

Исключение, которое вы, вероятно, относите к этому блоку своих кодов.

try { 
    JSONObject jo = response.getJSONObject(i); 
    // get the name of the student. We need to join first and last names 
    String f_name = jo.getString("fist_name"); 
    String l_name = jo.getString("last_name"); 
    String full_name = f_name + " " + l_name; 

    // get the roll number of the student 
    String roll_no = jo.getString("roll_number"); 
    TableRow detail_row = (TableRow) findViewById(R.id.row_att_detail); 
    ((TextView) detail_row.findViewById(R.id.txt_roll_no)).setText(roll_no); 
    ((TextView) detail_row.findViewById(R.id.txt_student_name)). 
             setText(full_name); 
    tableRows.add(detail_row); 
    tableLayout.addView(tableRows.get(i)); 
} 

Некоторые замечания, которые вы должны остерегаться:

  • Представления могут быть присоединены только к основной зрения иерархии только один раз. Таким образом, если вы попытаетесь снова присоединить уже прикрепленный вид к иерархии, вы получите исключение.

  • Если вы добавите ребенка в TableRow, вам не нужно будет добавлять это TableRow в начало TableLayout.

+0

Хорошо, но как я могу создать новый экземпляр tablerow с id row_att_detail в блоке try .. catch выше? –

+0

@Atulgupta Для получения нового экземпляра вы должны создать новый 'TableRow' по ключевому слову' new', а не 'findViewById'. –

+0

@Atulgupta http://stackoverflow.com/questions/7279501/programatically-adding-tablerow-to-tablelayout-not-working –

Смежные вопросы