【问题标题】:My ListView is null, why?我的 ListView 为空,为什么?
【发布时间】:2015-05-10 14:44:52
【问题描述】:

应用程序连接到 Web 服务: - 提取和解析 xml -> 工作 - 适配器 -> 工作

但是当我用 findViewById() 初始化 ListView (lstCustomers) 时,我不明白为什么?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String url = "myUrl.com";
    Log.d("CustomerREST", "Start Activity");


    try {
        RestCustomerAsync ctm = new RestCustomerAsync();
        ctm.execute(url);

        ArrayList<Customer> ctms = (ArrayList<Customer>) ctm.get();

        //CustomerAdapter adapter = new CustomerAdapter(this,R.layout.customer_row,ctms);
        CustomerAdapter adapter = new CustomerAdapter(getApplicationContext(), R.layout.customer_row, ctms);
        Log.d("CustomerREST", "Adapter OK");

        ListView lstCustomer = (ListView) findViewById(R.id.lstCustomers); // return null why ??
        Log.d("CustomerREST", "INIT LISTVIEW");

        lstCustomer.setAdapter(adapter);
        Log.d("CustomerREST", "Adapter to View");

    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
}

XML 布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<ListView
    android:id="@+id/lstCustomers"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

【问题讨论】:

  • 因为FindViewByID返回null,即没有找到与你提供的ID对应的视图。
  • 你从来没有 setContentView(R.layout.your_xml_layout);在调用 super.onCreate() 之后
  • 哦,是的,我忘了这个!!谢谢

标签: android listview android-studio


【解决方案1】:

我想你可能忘记打电话给setContentView(R.layout.your_layout)

【讨论】:

  • 哎呀!谢谢
【解决方案2】:

如果您的代码是片段:

onCreate 在实际创建视图之前触发。

请将您的代码移至 onViewCreated() 方法,如下所示:

public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    //here Your code.
}

如果您的代码在活动中:

setContentView(R.your_layout) 

onCreate 方法中。

【讨论】:

  • 我的代码在活动中,但感谢您提供信息。现在可以用了!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-26
  • 1970-01-01
  • 2016-09-04
  • 2018-06-26
  • 2010-11-25
相关资源
最近更新 更多