0
我有一個LinearLayout
和一個TableLayout
裏面的活動。我想以編程方式將數據添加到此表中,但每次遇到空指針異常。我試圖清理我的項目,但我仍然有此指令相同的錯誤空指針異常:向tableLayout添加新行時出現NullPointerException
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>
請顯示logcat日誌。 –
thx爲您的關注我的問題解決了我只需要使用LinearLayout而不是相對的我不是爲什麼,但它的工作原理和清理並重新重建項目 – elpazio
@elpazio而不是改變你的佈局,看看你的Logcat,看看爲什麼你得到一個NullPointerException。當你改變佈局時,你只是掩蓋了問題,並沒有真正解決未來可能導致你頭痛的問題。 – Pztar