java.lang.NullPointerException: 尝试调用虚方法 'android.view.View android.widget.TableRow.getChildAt(int)

java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.TableRow.getChildAt(int)

你好,对不起我的英语水平=)

我正在 Android Studio 中编写一个小计算程序,但遇到了问题。

我在 Table 布局中动态创建了 Table 行,如下所示:

    TableLayout table2 = (TableLayout) findViewById(R.id.table2);
    TableRow.LayoutParams rowParams = new TableRow.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL);

    TableRow row = new TableRow(this);
    row.setLayoutParams(rowParams);

    row.addView(floor2);
    row.addView(ps2table);
    row.addView(gsatable);
    row.addView(vitable);
    table2.addView(row);

其中 floor2、ps2table、gsatable 和 vitable - 是按下按钮后计算的 TextView。

创建 Table 后,我尝试使用其中一个数字(Table布局的最后一行和第 2 个位置的子项):

    int gsn_count = table2.getChildCount();
    TableRow gsnRow = (TableRow) table2.getChildAt(gsn_count);
    TextView tGsn = (TextView) gsnRow.getChildAt(2);

我的问题是,当我尝试从这个 TableLayout 的任何 Table 行中获取一个或另一个数字(双精度)的值时,我得到了这个错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.TableRow.getChildAt(int)' on a null object reference

它正在寻找我,因为我没有我所指的号码,但它在那里。我将在下面的链接中添加一张带有评论的图片和我的所有代码。

图片:http://i.imgur.com/huI4kba.png

我遇到错误的方法代码:http://pastebin.com/nDPnbHNR

谢谢!

试一试:

int gsn_count = table2.getChildCount();
TableRow gsnRow = (TableRow) table2.getChildAt(gsn_count -1);

getChildAt() 获取索引(从 0 开始)和 getChildCount() returns 子计数。

因此,如果您有 2 个项目,则最大索引为 1,计数为 2。