[英]Unable to populate ListView from ArrayList
ChooseCategory.java
public class ChooseCategory extends ListActivity {
private ListView lv;
//ArrayAdapter<FoodStores> arrayAdapter;
private ArrayList<FoodStores> storefoodList;
private String URL_STORES = "http://10.0.2.2/get_stores.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lv = (ListView)findViewById(R.id.list);
storefoodList = new ArrayList<FoodStores>();
new GetFoodStores().execute();
}
private class GetFoodStores extends AsyncTask<Void,Void,Void> {
@Override
protected void onPreExecute(){
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... arg0) {
ServiceHandlerFood jsonParserFood = new ServiceHandlerFood();
String json = jsonParserFood.makeServiceCall(URL_STORES, ServiceHandlerFood.GET);
Log.e("Response: ", " > " + json);
if(json != null){
try{
JSONObject jsonObj = new JSONObject(json);
if(jsonObj != null){
JSONArray storeListFood = jsonObj.getJSONArray("storelistfood");
for(int i = 0; i < storeListFood.length(); i++){
JSONObject storeFoodObj = (JSONObject) storeListFood.get(i);
FoodStores foodStores = new FoodStores(storeFoodObj.getInt("id"),storeFoodObj.getString("STORENAME"));
storefoodList.add(foodStores);
}
}
}catch(JSONException e){
e.printStackTrace();
}
}else{
Log.e("JSON Data", "No data received from server");
}
return null;
}
@Override
protected void onPostExecute(Void result){
super.onPostExecute(result);
populateListView();
}
}
這是我的populateListView的功能
private void populateListView(){
List<String> labels = new ArrayList<String>();
for(int i = 0; i < storefoodList.size(); i++){
labels.add(storefoodList.get(i).getName());
}
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this,R.layout.restaurant_list,labels);
Log.d("Labels:", labels.toString());
lv.setAdapter(listAdapter);
}
我在這里要做的是通過JSON從PHP到Android獲取商店列表,並將它們存儲在ArrayList中,然后將其填充到ListView中。 我嘗試顯示labels
,它顯示正確的內容。
來自Emulator的錯誤是它只顯示空白屏幕,然后崩潰。 來自logcat的錯誤是
java.lang.NullPointerException
at call.rocket.user.callarocket.ChooseCategory.populateListView
喜歡
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this,R.layout.restaurant_list,labels);
setListAdapter(listAdapter);
當您直接擴展ListActivity
也將其刪除
lv = (ListView)findViewById(R.id.list);
並確保您的ListView
ID為android:id="@android:id/list"
轉到教程
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.