The application is connected to a Web Service : - extract and parse the xml -> works - the adapter -> works
But when I init the ListView (lstCustomers) with findViewById() is null and I don't understand why ?
@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
<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.
Please move Your code to onViewCreated() method like this:
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.
我认为您可能忘记了调用setContentView(R.layout.your_layout)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.