IndexOutOfBound异常在pullToRefresh期间在ListView中向下滚动

时间:2015-09-24 11:12:57

标签: java android listview pull-to-refresh

向下滚动listview我收到IndexOutOfBound例外。

让我解释一下情景: -

首先,列表由我从服务器获取的数据填充。 - 没有错误

第二,当我 PULL TO REFRESH 获取数据时,同时当我滚动时,我得到IndexOutofBound Exception。 我陷入了这种情况。

请帮忙。

这是我的代码: -

NewOrders.java

公共类NewOrders扩展了Fragment工具         SwipeRefreshLayout.OnRefreshListener {

private ListView listView;
private SwipeRefreshLayout swipeRefreshLayout;
NewOrderListviewAdapter adp;
public static String allResId = "", boy_id = "";
String passedArg = "";
DialogView dialogView;
private Boolean isRefreshing = false;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_neworders,
            container, false);

    dialogView = new DialogView();

    listView = (ListView) rootView.findViewById(R.id.list);
    swipeRefreshLayout = (SwipeRefreshLayout) rootView
            .findViewById(R.id.swipe_refresh_layout);

    new getNewOrders().execute();

    swipeRefreshLayout.setOnRefreshListener(this);

    return rootView;
}

public class getNewOrders extends AsyncTask<Void, String, String> {

    String strMessage;

    @Override
    protected void onPreExecute() {

        // if (!PendingOrderListDataStorage.NEW_ORDER.isEmpty())
        // PendingOrderListDataStorage.NEW_ORDER.clear();

        // showing refresh animation before making http call
        swipeRefreshLayout.setRefreshing(true);

    }

    @Override
    protected String doInBackground(Void... params) {

        HttpClient httpClient = SessionControl.getHttpclient();
        String url = ServiceAPIs.PENDING_ORDER_LIST;
        HttpPost httppost = new HttpPost(url);

        try {
            List<NameValuePair> valuepair = new ArrayList<NameValuePair>();

            String resIds = "";

            for (int i = 0; i < PendingOrderListDataStorage.RESTAURANT_LIST
                    .size(); i++) {
                resIds = resIds
                        + ","
                        + PendingOrderListDataStorage.RESTAURANT_LIST
                                .get(i).restaurant_id;
            }

            resIds = resIds.substring(1);

            valuepair.add(new BasicNameValuePair("res_id", resIds));
            Log.d("RID", allResId);
            valuepair.add(new BasicNameValuePair("boy_id", passedArg));
            Log.d("BID", passedArg);

            httppost.setEntity(new UrlEncodedFormEntity(valuepair));

            HttpResponse httpResponse = httpClient.execute(httppost);
            StatusLine statusLine = httpResponse.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity httpEntity = httpResponse.getEntity();

                if (httpEntity != null) {

                    InputStream instream = httpEntity.getContent();
                    strMessage = Converter.inputStreamToString(instream)
                            .toString();
                }
            } else {
                return null;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            httpClient.getConnectionManager().closeExpiredConnections();
        }
        return strMessage;
    }

    @Override
    protected void onProgressUpdate(String... progress) {
        super.onProgressUpdate(progress);

    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        // stopping swipe refresh
        swipeRefreshLayout.setRefreshing(false);
        isRefreshing = false;

        Log.d("BID from Rending for Delivery", passedArg);

        if (result != null) {

            Log.v("Result", result);

            try {

                JSONObject jsonObj = new JSONObject(result);
                String status = jsonObj.getString("status");
                if (status.equals("0")) {
                    System.out.print("No Pending Orders");
                } else {

                    JSONArray array = jsonObj.getJSONArray("data");

                    if (array.length() > 0) {

                        for (int i = 0; i < array.length(); i++) {

                            JSONObject obj = array.getJSONObject(i);

                            if (obj.getString("delivery_boy_status")
                                    .equals("P")) {

                                String deliveryDate = "";

                                if (obj.getString("deliverydate").contains(
                                        "/")) {
                                    deliveryDate = convertDate(obj
                                            .getString("deliverydate"));
                                }

                                else {
                                    deliveryDate = obj
                                            .getString("deliverydate");
                                }

                                NewOrderListObjectItem ObjectItemData = new NewOrderListObjectItem(
                                        obj.getString("restaurant_name"),
                                        obj.getString("status"),
                                        obj.getString("delivery_boy_status"),
                                        obj.getString("app_order_status"),
                                        obj.getString("orderid"),
                                        obj.getString("ordergenerateid"),
                                        obj.getString("customer_id"),
                                        obj.getString("usertype"),
                                        obj.getString("customername"),
                                        obj.getString("customerlastname"),
                                        obj.getString("customeremail"),
                                        obj.getString("customercellphone"),
                                        obj.getString("customerlandline"),
                                        obj.getString("deliverydoornumber"),
                                        obj.getString("deliverystreet"),
                                        obj.getString("deliverylandmark"),
                                        obj.getString("deliveryarea"), obj
                                                .getString("cityname"), obj
                                                .getString("zipcode"),
                                        obj.getString("deliverystate"), obj
                                                .getString("deliverytype"),
                                        obj.getString("foodassoonas"),
                                        deliveryDate, obj
                                                .getString("deliverytime"),
                                        obj.getString("ordertotalprice"),
                                        obj.getString("payment_type"),
                                        obj.getString("paypal_status"), obj
                                                .getString("orderdate"));
                                // PendingOrderListDataStorage.NEW_ORDER
                                // .clear();

                                if (!PendingOrderListDataStorage.NEW_ORDER
                                        .isEmpty())
                                    PendingOrderListDataStorage.NEW_ORDER
                                            .clear();
                                PendingOrderListDataStorage.NEW_ORDER
                                        .add(ObjectItemData);

                            }

                        }

                    }
                }

                if (adp != null)
                    adp.notifyDataSetChanged();
                else
                    makeList();

            } catch (JSONException e) {
                e.printStackTrace();
                dialogView.showCustomToast(getActivity(), "Error");
            }

        } else {
            dialogView.showCustomToast(getActivity(),
                    "Please Check your Internet Connection");
        }
    }

    private void makeList() {
        Log.d("Size: From New Orders List", ""
                + PendingOrderListDataStorage.NEW_ORDER.size());
        if (PendingOrderListDataStorage.NEW_ORDER.size() > 0) {
            adp = new NewOrderListviewAdapter(getActivity(),
                    R.layout.order_item_new,
                    PendingOrderListDataStorage.NEW_ORDER);

            listView.setAdapter(adp);
            adp.notifyDataSetChanged();
        }

    }

    @SuppressLint("SimpleDateFormat")
    String convertDate(String inputDate) {
        SimpleDateFormat theDateFormat = new SimpleDateFormat("MM/dd/yyyy");
        Date date = null;

        try {
            date = theDateFormat.parse(inputDate);
        } catch (ParseException parseException) {
            // Date is invalid. Do what you want.
        } catch (Exception exception) {
            // Generic catch. Do what you want.
        }

        theDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        return theDateFormat.format(date);
    }
}

@Override
public void onRefresh() {
    swipeRefreshLayout.setRefreshing(true);

    if (!isRefreshing) {
        isRefreshing = true;

        new getNewOrders().execute();
    }

}

}

NewOrderListViewAdapter.java

@Override
public View getView(final int position, View convertView,
        final ViewGroup parent) {
    final ViewHolder holder;
    LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();

if (convertView == null) {

    convertView = inflater.inflate(layoutResourceId, null);

    holder = new ViewHolder();

    holder.btn_confirm = (TextView) convertView
            .findViewById(R.id.confirm);
    holder.btn_details = (TextView) convertView
            .findViewById(R.id.details);

    holder.title = (TextView) convertView.findViewById(R.id.title);

    holder.orderDateTime = (TextView) convertView
            .findViewById(R.id.orderDateTime);

    holder.deliveryDateTime = (TextView) convertView
            .findViewById(R.id.deliveryDateTime);

    holder.orderNumberCode = (TextView) convertView
            .findViewById(R.id.orderNumberCode);

    holder.orderAddressName = (TextView) convertView
            .findViewById(R.id.orderAddressName);

    convertView.setTag(holder);

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

NewOrderListObjectItem list = data.get(position);

holder.title.setText(list.getRestaurant_name());
Log.d("RestaurantName", list.getRestaurant_name());

holder.orderNumberCode.setText("#ORD " + list.getOrderid());
Log.d("Order No.:", "#ORD" + list.getOrderid());

holder.orderDateTime.setText(list.customername + " "
        + list.customerlastname);
Log.d("Order Date & Time", list.getOrderdate());

holder.deliveryDateTime.setText(list.getDeliverydate() + " "
        + list.getDeliverytime());
Log.d("Delivery Date & Time",
        list.getDeliverydate() + "" + list.getDeliverytime());

holder.orderAddressName.setText(list.getDeliverystreet() + ", "
        + list.getDeliveryarea() + ", " + list.getDeliverycity() + ", "
        + list.getDeliverystate() + ", " + list.getDeliverystate());

holder.btn_details.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {

        Intent next = new Intent(mContext, Orders.class);
        Bundle bundle = new Bundle();
        bundle.putString("order_id", holder.orderNumberCode.getText()
                .toString());
        Log.d("Order Id: ", holder.orderNumberCode.getText().toString());
        bundle.putString("order_status", order_status);
        Log.d("Order Status: ", order_status);
        bundle.putInt("gridPositionClicked", position);
        next.putExtras(bundle);
        mContext.startActivity(next);
        ((Activity) mContext).overridePendingTransition(
                R.anim.push_left_in, R.anim.push_left_out);
        ((Activity) mContext).finish();

    }
});

holder.btn_confirm.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {

        boy_id = GlobalVariable.boy_id_one;
        order_id = holder.orderNumberCode.getText().toString();
        Log.d("CONFIRM_BUTTON", order_id);
        new changeOrderStatus().execute();

    }

});

    return convertView;
}

1 个答案:

答案 0 :(得分:1)

您正在清除PendingOrderListDataStorage.NEW_ORDER.clear(); 在Asynctast的preExecute中,在将新数据添加到Asynctask的Onpostexecute中的列表之前清除数组。