简体   繁体   English

我的ListView为null,为什么?

[英]My ListView is null, why?

The application is connected to a Web Service : - extract and parse the xml -> works - the adapter -> works 该应用程序已连接到Web服务:-提取并解析xml->作品-适配器->作品

But when I init the ListView (lstCustomers) with findViewById() is null and I don't understand why ? 但是当我使用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 Layout 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" />

In case Your code is a fragment: 如果您的代码是片段:

onCreate is fired before view is in fact created. 实际上创建视图之前会触发onCreate

Please move Your code to onViewCreated() method like this: 请将您的代码移动到onViewCreated()方法,如下所示:

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

In case Your code is in Activity: 如果您的代码处于活动状态:

setContentView(R.your_layout) 

inside onCreate method. 里面的onCreate方法。

我认为您可能忘记了调用setContentView(R.layout.your_layout)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM