通过JSON排序获取数据后,自定义列表适配器不显示

时间:2017-07-17 06:51:55

标签: java android json

我一直在尝试使用volley库获取JSON数据。一切都很顺利,但数据没有显示在CustomListAdapter上。我认为问题出在Custom Adapter上。 Url for JSON没问题,数据已成功获取。代码如下。

CustomListAdapter.java代码

public class CustomListAdapter extends ArrayAdapter<food> {

private Activity act;
private ArrayList<food>data;
private int layoutResource;
public CustomListAdapter(@NonNull Activity activity, int resource, ArrayList<food>items) {
    super(activity, resource, items);

    act=activity;
    data=items;
    layoutResource=resource;

}

@Override
public int getCount() {
    return data.size();
}

@Nullable
@Override
public food getItem(int position) {
    return super.getItem(position);
}

@Override
public int getPosition(@Nullable food item) {
    return super.getPosition(item);
}

@Override
public long getItemId(int position) {
    return super.getItemId(position);
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    View row=convertView;
    ViewHolder holder=null;

    if(row==null || (row.getTag()==null)){
        LayoutInflater inflater=LayoutInflater.from(act);
        row=inflater.inflate(layoutResource,parent,false);

        holder=new ViewHolder();

        //get references to views
        holder.ItemName=(TextView)row.findViewById(R.id.listName);

        row.setTag(holder);

    }else{
        holder=(ViewHolder)row.getTag();
    }

    holder.foodItem=data.get(position);

    //we can now display data
    holder.ItemName.setText(holder.foodItem.getItemName());

    final ViewHolder finalHolder = holder;
    row.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i=new Intent(act, FoodDetails.class);
            Bundle mbundle=new Bundle();
            mbundle.putSerializable("bundleOnj", finalHolder.foodItem);
            i.putExtras(mbundle);
            act.startActivity(i);
        }
    });
    return row;
}

public class ViewHolder{
    TextView ItemName;
    food foodItem;
}
}

ListActivity.java代码;在此代码中,当我使用setText获取JSON对象时,它正在正常运行。

public class ListActivity extends AppCompatActivity {

private CustomListAdapter adapter;
private ListView listview;
private ArrayList<food>foodItems=new ArrayList<>();
private String LEFT_URL="https://api.nutritionix.com/v1_1/search/";
private String  RIGHT_URL="?fields=item_name%2Citem_id%2Cbrand_name%2Cnf_calories%2Cnf_total_fat&appId=MY_IDd&appKey=MY_API";
private TextView selectedItem;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list);

    listview=(ListView)findViewById(R.id.listView);
    selectedItem=(TextView)findViewById(R.id.selectedItem);
    adapter=new CustomListAdapter(ListActivity.this,R.layout.row,foodItems);
    listview.setAdapter(adapter);

    getFoodDetails("Butter");
}

private void getFoodDetails(String item){
    //clear data first
    foodItems.clear();

    String FINAL_URL=LEFT_URL+item+RIGHT_URL;

    JsonObjectRequest foodObjectRequest=new JsonObjectRequest(Request.Method.GET,
            FINAL_URL, (JSONObject) null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

            try{
                JSONArray foodArray= response.getJSONArray("hits");

                for(int i=0;i<foodArray.length();i++){
                    JSONObject JsonObject=foodArray.getJSONObject(i);
                    JSONObject fieldsObject=JsonObject.getJSONObject("fields");

                    //get the Json Details

                    String itemName=fieldsObject.getString("item_name");
                    //selectedItem.setText("item Selected: "+itemName);
                    String brand_name=fieldsObject.getString("brand_name");
                    selectedItem.setText("item Selected: "+brand_name);
                    String servingSizeUnit=fieldsObject.getString("nf_serving_size_unit");
                    double calories=fieldsObject.getDouble("nf_calories");
                    //selectedItem.setText("item Selected: "+calories);
                    double fat=fieldsObject.getDouble("nf_total_fat");


                    //putting data to set functions
                    food foodInfo=new food();
                    foodInfo.setBrandName(brand_name);
                    foodInfo.setItemName(itemName);
                    foodInfo.setCalories(calories);
                    foodInfo.setFat(fat);
                    foodInfo.setServingSizeunit(servingSizeUnit);

                    foodItems.add(foodInfo);
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    AppController.getInstance().addToRequestQueue(foodObjectRequest);
}
}

2 个答案:

答案 0 :(得分:0)

将对象添加到列表后

调用adapter.notifyDataSetChanged()

答案 1 :(得分:0)

您在获取数据之前设置适配器。 检索数据后设置适配器。

onCreate中的

删除此行

listview.setAdapter(adapter);
在for循环之后的getFoodDetails中

添加此行

listview.setAdapter(adapter);