向tableLayout添加新行时出现NullPointerException

时间:2015-07-10 16:17:09

标签: android android-tablelayout

我的活动中包含LinearLayoutTableLayout。我想以编程方式将数据添加到此表,但每次我得到空指针异常。我试图清理我的项目但是在这条指令中仍然有相同的错误空指针异常:

iptable.addView(tr_head, new TableLayout.LayoutParams(
       TableLayout.LayoutParams.FILL_PARENT,
        TableLayout.LayoutParams.WRAP_CONTENT));

我使用OnCreate方法:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_iposition);
    session=new SessionManager(getApplicationContext());
    ActionBar actionbar=getSupportActionBar();
    actionbar.setDisplayHomeAsUpEnabled(true);

    TableLayout iptable = (TableLayout) findViewById(R.id.ip_table);

    TableRow tr_head = new TableRow(this);
    tr_head.setId(10);
    tr_head.setBackgroundColor(Color.GRAY);

    TextView label_Item = new TextView(this);
    label_Item.setId(20);
    label_Item.setText("Valeur");
    label_Item.setTextColor(Color.WHITE);
    label_Item.setPadding(5, 5, 5, 5);
    tr_head.addView(label_Item);

    TextView label_Quantity = new TextView(this);
    label_Quantity.setId(21);
    label_Quantity.setText("Quantite"); 
    label_Quantity.setTextColor(Color.BLACK);
    label_Quantity.setPadding(5, 5, 5, 5); 
    tr_head.addView(label_Quantity); 

    tr_head.setLayoutParams(new TableRow.LayoutParams(
            TableRow.LayoutParams.FILL_PARENT,
            TableRow.LayoutParams.WRAP_CONTENT));
    iptable.addView(tr_head, new TableLayout.LayoutParams(
           TableLayout.LayoutParams.FILL_PARENT,
            TableLayout.LayoutParams.WRAP_CONTENT));

activity_iposition中,我有:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    ...
    android:background="@drawable/itempositionlayout">

    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:stretchColumns="0,1"
        android:id="@+id/ip_table" android:layout_weight="1" android:layout_height="wrap_content" android:layout_width="match_parent">
    </TableLayout>
</RelativeLayout>

1 个答案:

答案 0 :(得分:1)

解决方案是清理项目并重建它,一切正常...我移动代码相对于在新方法中添加新行以在onCreate方法结束时调用它我得到NullPointerException