我的活动中包含LinearLayout
和TableLayout
。我想以编程方式将数据添加到此表,但每次我得到空指针异常。我试图清理我的项目但是在这条指令中仍然有相同的错误空指针异常:
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>
答案 0 :(得分:1)
解决方案是清理项目并重建它,一切正常...我移动代码相对于在新方法中添加新行以在onCreate方法结束时调用它我得到NullPointerException