我的ListView为空,为什么?

时间:2015-05-10 14:44:52

标签: android listview android-studio

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

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

@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" />

2 个答案:

答案 0 :(得分:0)

如果您的代码是片段:

在实际创建视图之前触发

onCreate

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

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

如果您的代码在Activity中:

setContentView(R.your_layout) 

onCreate 方法内。

答案 1 :(得分:0)

我想您可能忘记致电setContentView(R.layout.your_layout)