繁体   English   中英

我的ListView为null,为什么?

[英]My ListView is null, why?

该应用程序已连接到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" />

如果您的代码是片段:

实际上创建视图之前会触发onCreate

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

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

如果您的代码处于活动状态:

setContentView(R.your_layout) 

里面的onCreate方法。

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

暂无
暂无

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

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