簡體   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