[英]Unable to populate ListView from ArrayList
ChooseCategory.java 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();
}
}
Here is the function of my 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);
}
What I am trying to do here is to get the list of stores from PHP to Android via JSON and store them in ArrayList and then populate them into ListView. 我在这里要做的是通过JSON从PHP到Android获取商店列表,并将它们存储在ArrayList中,然后将其填充到ListView中。 I have tried displaying
labels
, it is displaying the correct stuff. 我尝试显示
labels
,它显示正确的内容。
The error from Emulator is that it just shows blank screen and then it crashes. 来自Emulator的错误是它只显示空白屏幕,然后崩溃。 The error from logcat is
来自logcat的错误是
java.lang.NullPointerException
at call.rocket.user.callarocket.ChooseCategory.populateListView
Do like 喜欢
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this,R.layout.restaurant_list,labels);
setListAdapter(listAdapter);
as you directly extends ListActivity
also remove 当您直接扩展
ListActivity
也将其删除
lv = (ListView)findViewById(R.id.list);
and make sure your ListView
id is android:id="@android:id/list"
并确保您的
ListView
ID为android:id="@android:id/list"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.