Search code examples
androidandroid-tablelayout

Table Layout not showing & getChildCount caused exception, android


I experiment with the table layout using one of the documented examples. With a barebone MainActivity that just has the following code up to setContentView(R.layout.activity_main), the emulator showed the table layout fine. I then added the lines after the setContentView line and that action caused :

  1. the layout not showing in the emulator (even after executing passed the setContentView line, when the code stopped at a breakpoint on the tableLayout declaration line)
  2. error at the line with the first getChildCount().

The code in the MainActivity is shown below:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    TableLayout tableLayout = null;
    int s = tableLayout.getChildCount(); 

    for(int n = 0; n < s; ++n) {
        TableRow row = (TableRow)tableLayout.getChildAt(n);
        int t = row.getChildCount();

}

What have I missed? Thanks for your help in advance.


Solution

  • You have to initialise your TableLayout tableLayout like this:

    TableLayout tableLayout = findViewById(R.id.whatever_id_you_gave_to_the_tablelayout);