0

I am trying to add a tableLayout at runtime to the existing LinearLayout in main.xml. I have added a editText(R.id.editText1) in the main.xml. Here's my code. Its not working. I get a runtime error (The application has stopped unexpectedly).

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    text = (EditText)findViewById(R.id.editText1);
    TableLayout tblLayout = new TableLayout(this);
    tblLayout.setLayoutParams(new TableLayout.LayoutParams(8,5));
    tblLayout.setPadding(1,1,1,1);

    for(int r=0; r<ROW_COUNT; ++r)
    {
        TableRow tr = new TableRow(this);
        for(int c=0; c<COL_COUNT; ++c)
        {
            int index = r * COL_COUNT + c;
            buttonList.add(new Button(this));
            buttonList.get(index).setText(buttonNames[index]);
            tr.addView(buttonList.get(index), 60, 30);
        }
        tblLayout.addView(tr);
    }

    LinearLayout mainLayout = (LinearLayout)findViewById(R.layout.main);
    mainLayout.addView(tblLayout);        

    setContentView(mainLayout);
}

Any pointers would be greatly appreciated. Thanks.

Happy Go Lucky
  • 607
  • 1
  • 9
  • 17
  • Paste your logcat. It could be any number of reasons... For example, buttonList might be null (did you instantiate it?) – IncrediApp Aug 30 '11 at 09:11
  • As per the logcat, the error seems to be happening in this line CalculatorActivity.java:46 which is mainLayout.addView(tblLayout); I have instantiated buttonList. – Happy Go Lucky Aug 30 '11 at 09:24

3 Answers3

0

Before your loop add :

Arraylist<TableRow> tr = new ArrayList<TableRow>;

In the loop instead of :

TableRow tr = new TableRow(this);

Put :

tr.add(new TableRow(this));

And finally replace your tr by tr.get(r). Something like these modifications should help you because, you erase your tr at each turn of your loop with your :

TableRow tr = new TableRow(this);
mthpvg
  • 3,789
  • 3
  • 26
  • 34
0

Mr. Happy Go Lucky just do one thing write setContentView(R.layout.your Main Layout); beofre text = (EditText)findViewById(R.id.editText1); means at top of the onCreate() method because we cant define any view before setContentView.

without any setContentView you cant find any view like as findViewById(R.id.editText1);

Niranj Patel
  • 32,980
  • 10
  • 97
  • 133
0

Below line will be the first one after super.onCreate(savedInstanceState);

 setContentView(mainLayout);

then only findViewByid works

ingsaurabh
  • 15,249
  • 7
  • 52
  • 81