gpt4 book ai didi

java - 无法从 ArrayList 填充 ListView

转载 作者:行者123 更新时间:2023-12-02 04:36:15 25 4
gpt4 key购买 nike

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 中。我尝试过显示标签,它显示了正确的内容。

模拟器的错误是它只显示空白屏幕然后崩溃。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"

转到Tutorial

关于java - 无法从 ArrayList 填充 ListView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30707411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com