如何在android中取消volly请求?

时间:2016-08-24 03:52:04

标签: android

当用户向下滚动请求被发送到服务器以获取更多数据时,我有一个包含Listview的活动请求通过参数count = 5(它始终是静态的)发送并且last = 5并且再次向下滚动最后变为10并且我想当服务器响应是“没有项目”然后我想取消凌空请求列表视图向下滚动。我怎么能这样做

Listview的代码向下滚动;

@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
    if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && bBottomOfView) {
        Log.i("Listview", "scrolling stopped...");
        if (NetworkUtil.isConnected(getActivity())) {
            m_n_DefaultRecordCount = 5;// increment of record count by 5 on next load data
            m_n_DeafalutLastCount = m_n_DeafalutLastCount + 5;// same here.....as above

            sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// convert int value to string
            sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// convert int value to string /////
            Log.e(TAG, "Last Count::" + sz_LastCount);
            Log.e(TAG, "Record count::" + sz_RecordCount);


            loadmoreData();


        } else {
            CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "Please check internet connection !", getActivity());
            m_ListView.removeFooterView(mFooter);
        }

    }
}

和用于加载更多数据的代码

public void loadmoreData() {

    try {
        String json;
        // 3. build jsonObject
        final JSONObject jsonObject = new JSONObject();// making object of Jsons.
        jsonObject.put("agentCode", m_szMobileNumber);// put mobile number
        jsonObject.put("pin", m_szEncryptedPassword);// put password
        jsonObject.put("recordcount", sz_RecordCount);// put record count
        jsonObject.put("lastcountvalue", sz_LastCount);// put last count
        Log.d("CAppList:", sz_RecordCount);
        Log.d("Capplist:", sz_LastCount);
        // 4. convert JSONObject to JSON to String
        json = jsonObject.toString();// convert Json object to  string
        Log.i(TAG, "Server Request:-" + json);
        requestQueue = Volley.newRequestQueue(getActivity());
        final String m_DealListingURL = "http://202.131.144.1:8080/json/metallica/getDealListInJSON";

        jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, m_DealListingURL, jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.i(TAG, "Server Response:-" + response);
                try {
                    int nResultCodeFromServer = Integer.parseInt(response.getString("resultcode"));
                    if (nResultCodeFromServer == m_TRANSACTION_SUCCESSFUL) {
                        JSONArray posts = response.optJSONArray("dealList");// GETTING DEAL LIST
                        for (int i = 0; i < posts.length(); i++) {
                            JSONObject post = posts.getJSONObject(i);// GETTING DEAL AT POSITION AT I
                            item = new CDealAppDatastorage();// object create of DealAppdatastorage
                            item.setM_szHeaderText(post.getString("dealname"));//getting deal name
                            item.setM_szsubHeaderText(post.getString("dealcode"));// getting deal code
                            item.setM_szDealValue(post.getString("dealvalue"));

                            if (!s_oDataset.contains(item)) {
                                s_oDataset.add(item);
                            }
                        }
                        m_oAdapter.notifyDataSetChanged();
                    }
                    if (nResultCodeFromServer == m_kCONNECTION_LOST) {//server based conditions
                        CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "Connection Lost !", getActivity());
                    } else if (nResultCodeFromServer == m_kDEAL_NOT_FOUND) {// serevr based conditions .....
                        CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "No more deals available", getActivity());

                        if (m_ListView.getFooterViewsCount() != 0) {
                            m_ListView.removeFooterView(mFooter);
                        }

                    } else if (nResultCodeFromServer == m_kTECHNICAL_FAILURE) {
                        CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "Technical Failure", getActivity());
                    } else if (nResultCodeFromServer == m_kALREADY_AVAIL_BENEFIT) {
                        CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "You have already avail the benefit of this deal", getActivity());
                    } else if (nResultCodeFromServer == m_kTIMED_OUT) {
                        CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "Timed Out", getActivity());
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                System.out.println("Error:-" + error);
                if (error instanceof TimeoutError) {
                    CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "Connection lost ! Please try again", getActivity());
                } else if (error instanceof NetworkError) {
                    CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "No internet connection", getActivity());
                }
            }
        });
        requestQueue.add(jsonObjectRequest);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

1 个答案:

答案 0 :(得分:1)

您可以取消下面的请求

您必须为每个请求添加标记,以便取消对特定标记的所有请求。

{
  "size": 0,
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "date": {
              "gt": "2016-08-22T00:00:00.000Z",
              "lt": "2016-08-22T13:41:09.000Z"
            }
          }
        },
        {
          "term": {
            "service": "http"
          }
        },
        {
          "term": {
            "destination": "10.17.102.1"
          }
        }
      ]
    }
  },
  "aggs": {
    "group_by_ip": {
      "terms": {
        "field": "ip"
      }
    }
  }
}

取消

<强> public static final String TAG = "MyTag"; StringRequest stringRequest; // Assume this exists. RequestQueue mRequestQueue; // Assume this exists. // Set the tag on the request. stringRequest.setTag(TAG); // Add the request to the RequestQueue. mRequestQueue.add(stringRequest);

请参阅此How to cancel volley request