如何取消Android中的单个截击请求?

时间:2016-09-22 06:27:31

标签: android

我有MainActivity添加Fragment发送服务器请求并包含ListView并刷卡刷新,问题是当我向下滑动以刷新它是发送服务器请求时同时,如果我按设备后退应用程序将在此时应用程序崩溃存在。如何实现此问题。

用于刷卡以刷新发送服务器请求的代码。

mSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            /*Here check net connection avialable or not */
            if (NetworkUtil.isConnected(getActivity())) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// convert int value to string
                        int length = preferences.getInt("length", 0);
                        sz_LastCount = String.valueOf(length);// convert int value to string /////

                        Log.e(TAG, "Last Count::" + sz_LastCount);
                        Log.e(TAG, "Record count::" + sz_RecordCount);
                        /*Send Request to Server for more data */
                        loadmoreOnSwipe();
                    }
                }, 3500);

            } else {
                CSnackBar.getInstance().showSnackBarError(m_MainLayout, "No internet connection available", getActivity());
                if (mSwipeRefresh.isRefreshing()) {

                    mSwipeRefresh.setRefreshing(false);
                }
            }
        }
    });

/*This method send request to server for more deals*/
private void loadmoreOnSwipe() {
    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);

        final String m_DealListingURL = "http://202.131.144.132:8080";
        JsonObjectRequest 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);
                if (mSwipeRefresh.isRefreshing()) {
                    mSwipeRefresh.setRefreshing(false);
                }
                try {
                    int nResultCodeFromServer = Integer.parseInt(response.getString("resultcode"));

                    if (nResultCodeFromServer == CStaticVar.m_kTRANSACTION_SUCCESS) {
                        // Select the last row so it will scroll into view...
                        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();
                        arrayCount = posts.length();// finding length of deals coming in response from server.
                        // read stored value from shared preference
                        int length = preferences.getInt("length", 0);

                        /*adding current array count with earlier saved value in shared preference*/
                        int accumulateLastCount = length + arrayCount;


                        /*Here we are saving deal length in shared preference*/
                        // save incremental length
                        SharedPreferences.Editor editor = preferences.edit();
                        editor.putInt("length", accumulateLastCount);
                        editor.apply();
                        // int add = CLastCountData.getInstance().getS_szLastCount() + arrayCount;
                        //CLastCountData.getInstance().setS_szLastCount(add);
                        m_ListView.removeFooterView(mFooter);
                        m_ListView.setSelection(m_oAdapter.getCount() - posts.length());

                    }

                    if (nResultCodeFromServer == CStaticVar.m_kCONNECTION_LOST) {//server based conditions
                        CSnackBar.getInstance().showSnackBarError(m_MainLayout, "Connection Lost !", getActivity());
                        m_ListView.removeFooterView(mFooter);
                    } else if (nResultCodeFromServer == CStaticVar.m_kDEAL_NOT_FOUND) {// serevr based conditions .....
                        CSnackBar.getInstance().showSnackBarError(m_MainLayout, "No more deals available", getActivity());
                        //*Counting loading footer*/
                        if (m_ListView.getFooterViewsCount() != 0) {
                            m_ListView.removeFooterView(mFooter);
                        }
                    } else if (nResultCodeFromServer == CStaticVar.m_kTECHNICAL_FAILURE) {
                        CSnackBar.getInstance().showSnackBarError(m_MainLayout, "Technical Failure", getActivity());
                    } else if (nResultCodeFromServer == CStaticVar.m_kALREADY_AVAIL_BENEFIT) {
                        CSnackBar.getInstance().showSnackBarError(m_MainLayout, "You have already avail the benefit of this deal", getActivity());
                    } else if (nResultCodeFromServer == CStaticVar.m_kTIMED_OUT) {
                        CSnackBar.getInstance().showSnackBarError(m_MainLayout, "Timed Out", getActivity());
                        m_ListView.removeFooterView(mFooter);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                System.out.println("Error:-" + error);
                if (mSwipeRefresh.isRefreshing()) {
                    mSwipeRefresh.setRefreshing(false);
                }
                if (error instanceof TimeoutError) {
                    CSnackBar.getInstance().showSnackBarError(m_MainLayout, "Connection lost ! Please try again", getActivity());
                } else if (error instanceof NetworkError) {
                    CSnackBar.getInstance().showSnackBarError(m_MainLayout, "No internet connection", getActivity());
                }
            }
        });

        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        requestQueue.add(jsonObjectRequest);

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

1 个答案:

答案 0 :(得分:2)

您可以为您的请求设置标记。它将是每个请求的标识。之后,您的请求队列有一个cancelAll方法,它需要一个标记。

//在将请求添加到队列之前,设置标记,标记可以是字符串,或者像那样。

yourRequest.setTag(tag);

之后,如果您想取消请求:

requestQueue.cancelAll(tag);