如何在列表视图中获取所选项目ID,而listview是根据名称排序的?

时间:2016-09-07 09:30:16

标签: android json listview android-volley

我从json获取数据并在listview中显示。我使用Comparator根据名称对listview进行了排序。问题是,当我点击排序列表视图时,它获取第一个项目的ID而不是已排序项目的ID。任何人都告诉我如何解决这个问题问题??

这是我的json数据: -

{
  "status": 1,
  "StatusMessage": "Restaurent List",
  "data": [
    {
      "ID": "7",
      "RestaurantName": "Water Lemon",
      "MinimumOrder": "20.000",
      "DeliveryTime": "",
      "OpenStatus": true,
      "PaymentOptions": "VISA, MasterCard , Maestro , American Express",
      "Is New Restaurant": true,
      "Is Provide Offer": true
    },
    {
      "ID": "8",
      "RestaurantName": "Casper and Gambini",
      "MinimumOrder": "40.000",
      "DeliveryTime": "",
      "OpenStatus": true,
      "PaymentOptions": "VISA, MasterCard , Maestro , American Express",
      "Is New Restaurant": true,
      "Is Provide Offer": true
    },
    {
      "ID": "11",
      "RestaurantName": "B L E N D S",
      "MinimumOrder": "50.000",
      "DeliveryTime": "",
      "OpenStatus": true,
      "PaymentOptions": "VISA, MasterCard , Maestro , American Express",
      "Is New Restaurant": true,
      "Is Provide Offer": true
    },
    {
      "ID": "12",
      "RestaurantName": "khyber Indian Cuisine",
      "MinimumOrder": "5.000",
      "DeliveryTime": "",
      "OpenStatus": true,
      "PaymentOptions": "VISA, MasterCard , Maestro , American Express",
      "Is New Restaurant": true,
      "Is Provide Offer": true
    },
    {
      "ID": "13",
      "RestaurantName": "Khyber Indian",
      "MinimumOrder": "5.000",
      "DeliveryTime": "",
      "OpenStatus": true,
      "PaymentOptions": "VISA, MasterCard , Maestro , American Express",
      "Is New Restaurant": true,
      "Is Provide Offer": true
    },
    {
      "ID": "14",
      "RestaurantName": "test",
      "MinimumOrder": "10.000",
      "DeliveryTime": "",
      "OpenStatus": true,
      "PaymentOptions": "VISA, MasterCard , Maestro , American Express",
      "Is New Restaurant": true,
      "Is Provide Offer": true
    },
    {
      "ID": "15",
      "RestaurantName": "yahoo",
      "MinimumOrder": "5.000",
      "DeliveryTime": "",
      "OpenStatus": true,
      "PaymentOptions": "VISA, MasterCard , Maestro , American Express",
      "Is New Restaurant": true,
      "Is Provide Offer": true
    },
    {
      "ID": "16",
      "RestaurantName": "Khaber",
      "MinimumOrder": "3.000",
      "DeliveryTime": "",
      "OpenStatus": true,
      "PaymentOptions": "VISA, MasterCard , Maestro , American Express",
      "Is New Restaurant": true,
      "Is Provide Offer": true
    },

这是方法()我解析json并在listview中显示: -

 public void requestRestaurantSearchByFilter_list() {
  mProgressDialog.show();
        StringRequest restrolistrequestfilter = new StringRequest(Request.Method.POST, GlobalData.SEARCHBYFILTERURL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {

                            mProgressDialog.dismiss();
                            mPaymentMethodList.clear();
                            mDataList.clear();
                            mAllList.clear();
                            mAdapter.notifyDataSetChanged();



                            JSONObject jObject = new JSONObject(response);
                            if (jObject.getString("status").equals("1")) {


                                JSONArray jsonArray = jObject.getJSONArray("data");
                                for (int i = 0; i < jsonArray.length(); i++) {


                                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                                    PojoRestaurant pojoRestaurant = new PojoRestaurant();


                                    pojoRestaurant.setRestroName(jsonObject.getString("RestaurantName"));
                                    pojoRestaurant.setDeliveryTime(jsonObject.optString("DeliveryTime"));
                                    pojoRestaurant.setPaymentOption(jsonObject.getString("PaymentOptions"));
                                    pojoRestaurant.setMinimumOrder(jsonObject.getString("MinimumOrder"));


                                    if (jsonObject.getString("ImageUrl").equals("") || jsonObject.getString("ImageUrl") == "null") {


                                    } else {


                                        pojoRestaurant.setRestroImage(jsonObject.getString("ImageUrl"));

                                    }

                                    id = jsonObject.getString("ID");

                                    pojoRestaurant.setRestroId(id);

                                    mPaymentMethodList.add(jsonObject.getString("PaymentOptions"));


                                    if (jsonObject.getString("OpenStatus").equals("true")) {

                                        pojoRestaurant.setOpenClose("Open");


                                    } else {
                                        pojoRestaurant.setOpenClose("Close");


                                    }

                                    mAllList.add(pojoRestaurant);
                                    mDataList.add(pojoRestaurant);

                                    Collections.sort(mDataList, RestaurantList.getCompByName());

                                    getpaymentId.add(id);
                                    getListViewId.add(id);
                                   }

                                mListView.setAdapter(mAdapter);
                                mAdapter.notifyDataSetChanged();

                            } else {

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {

                        Log.e("error", "" + volleyError.getMessage());
                        if (volleyError.getMessage() == null)
                            requestRestaurantSearchByFilter_list();


                    }
                }) {


            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                Map<String, String> params = new HashMap<String, String>();

                String foodid = getArguments().getString("FOODID");
                String areaid = getArguments().getString("AREAID");



                params.put("DeliveryAreaID", areaid);
                params.put("ProvideOffers", "0");
                params.put("NewRestaurant", "0");
                params.put("PaymentMethod", "0");
                params.put("OpenRestaurant", "0");
                params.put("FoodID", foodid);

                return params;
            }


        };

        RequestQueue restrolistqueuefilter = Volley.newRequestQueue(getContext());
        restrolistrequestfilter.setShouldCache(false);
        restrolistqueuefilter.add(restrolistrequestfilter);


    } 

这是我的Comparator方法(),通过它我可以根据restro名称设置listview。 : -

public static Comparator<PojoRestaurant> getCompByName() {
        Comparator<PojoRestaurant> comp = new Comparator<PojoRestaurant>() {
            @Override
            public int compare(PojoRestaurant lhs, PojoRestaurant rhs) {
                return lhs.RestroName.compareTo(rhs.RestroName);
            }
        };
        return comp;
    }

以下是listview上的点击列表器,我获取listview项的位置并获取listview项的id: -

 mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
              mListViewItemId = getListViewId.get(i);
             Fragment fragment = new RestrurantName();
                Bundle b = new Bundle();
                b.putString("ListViewitemId", mListViewItemId);

                fragment.setArguments(b);


                getFragmentManager().beginTransaction().replace(R.id.frame, fragment).addToBackStack(null).commit();
                toolbar.setTitle("Restaurant Name");

            }
        });

其中getListViewId是字符串类型的数组列表。

这是我的Adapter类: -

public class RestroListBaseAdapter extends BaseAdapter {

    private ArrayList<PojoRestaurant> mList;
    private Context mContext;
    private ViewHolder viewHolder;


    public RestroListBaseAdapter(Context mContext, ArrayList<PojoRestaurant> mList) {

        this.mContext = mContext;
        this.mList = mList;


    }


    @Override
    public int getCount() {
        if (mList != null) {
            return mList.size();

        }


        return 0;
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        int lastPosition = -1;
        LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null) {
            convertView = layoutInflater.inflate(R.layout.restaurant_item, parent, false);
            viewHolder = new ViewHolder();
            viewHolder.RestroName = (TextView) convertView.findViewById(R.id.tv_restro_name);
            viewHolder.OpenClose = (TextView) convertView.findViewById(R.id.tvOpenClose);
            viewHolder.MinimumOrder = (TextView) convertView.findViewById(R.id.tv_minimun_order);
            viewHolder.DeliveryTime = (TextView) convertView.findViewById(R.id.tv_delivery_time);
            viewHolder.PaymentOption = (TextView) convertView.findViewById(R.id.tv_Payment);
            viewHolder.RestroImage = (ImageView) convertView.findViewById(R.id.img_restro_list);


        } else {

            viewHolder = (ViewHolder) convertView.getTag();


        }


        Animation animation = AnimationUtils.loadAnimation(mContext, (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
        convertView.startAnimation(animation);
        lastPosition = position;


        convertView.setTag(viewHolder);

        PojoRestaurant pojoRestaurant = (PojoRestaurant) getItem(position);

        viewHolder.RestroName.setText(pojoRestaurant.getRestroName());
        viewHolder.DeliveryTime.setText(pojoRestaurant.getDeliveryTime());
        viewHolder.MinimumOrder.setText(pojoRestaurant.getMinimumOrder());
        viewHolder.OpenClose.setText(pojoRestaurant.getOpenClose());
        viewHolder.PaymentOption.setText(pojoRestaurant.getPaymentOption());
        Picasso.with(mContext).load(pojoRestaurant.getRestroImage()).into(viewHolder.RestroImage);


        return convertView;
    }



    private class ViewHolder {
        private TextView RestroName, OpenClose, MinimumOrder, DeliveryTime, PaymentOption;
        private ImageView RestroImage;

    }


}

问题: - 当我从列表视图中选择项目时,id(mListViewItemId)将相应地采用json id。我希望当我选择特定项目时,它会获取该项目的ID。 在我的情况下,当我选择Restro名称(B L E N D S)时,它将获取id 7.请看我的json并告诉我该怎么做?

1 个答案:

答案 0 :(得分:0)

从你的代码中我可以看到你已经对mDataList arraylist进行了排序以获得排序列表。但是您已将id列表存储在单独的列表中,该列表是您未排序的getListViewId

如果您对mDataList进行排序,那么您还必须对getListViewId列表进行排序以获得正确的列表。

但我建议您仅从mDataList获取列表项ID,如下所示

    mListViewItemId = mDataList.get(i).getRestroId();

希望这会指导你。如果有任何疑问,请告诉我。