【发布时间】: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