Search code examples
javaandroidtablerowandroid-contexttimetable

Array of tablerows - can't give it context?


So for my code, I'm trying to fill a timetable with data from a database. The best way for me to do this is to create a blank timetable, then fill it in afterwards. I know exactly how many rows I need, so I'm using an array of TableRows, then adding a certain amount of TextViews to each row.

However, it crashes after every run. I think it may have something to do with the tablerows not having context? Here's all the relevant code, I'd really appreciate it if someone could help me out.

public class Timetable123 extends Activity {
    TableRow[] row= new TableRow[36];  //declared at start

    InitializeTable(SortedDatesList.toArray(new String[SortedDatesList.size()])); // List converted to array sent to initializeTable

}

    private void InitializeTable(String...params){


        for(int i=0;i<36;i++) {
            row[i].setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
            try {
                for (Integer j = 0; j < (params.length+1); j++) {
                    TextView tv = new TextView(this);
                    tv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
                            TableRow.LayoutParams.WRAP_CONTENT));
                    tv.setBackgroundResource(R.drawable.cell_shape);
                    tv.setPadding(5, 5, 5, 5);
                    row[i].addView(tv);
                    System.out.println(params[i] + " run " + i);
                }
            } catch (Exception ex) {
                System.out.println(ex);
            }
        }
    }

It always crashes when initializeTable is called, and I really can't figure out why.


Solution

  • Creating Array of type TableRow but not adding TableRow object before accessing TableRow from Array :

     for(int i=0;i<36;i++) {
       row[i]=new TableRow(Timetable123.this); //<< Create Object here
       row[i].setLayoutParams(new 
               TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                            TableRow.LayoutParams.WRAP_CONTENT));
    ...
    }