【问题标题】:NullPointerException when adding a new row to tableLayout向 tableLayout 添加新行时出现 NullPointerException
【发布时间】:2015-07-11 00:40:59
【问题描述】:

我有一个活动,里面有一个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>

【问题讨论】:

  • 请显示 logcat 日志。
  • 感谢您的关注,我的问题已解决,我只需要使用 LinearLayout 而不是相对的,我不知道为什么,但它可以工作并再次清理和重建项目
  • @elpazio 而不是更改您的布局,而是查看您的 Logcat 以了解为什么您会收到 NullPointerException。当您更改布局时,您只是掩盖了问题,并没有真正解决将来可能导致您头疼的问题。
  • 实际上它不是完全是它正在清理和重建项目的布局

标签: android android-tablelayout


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多