2

I have a MainActivity which adds a Fragment which send server request and contained a ListView with swipe to refresh ,Problem is that when I swipe down to refresh it is sending server request at the same time if I press device back app will exist at this point of time app crash.How to achieve this problem.

code for on swipe to refresh send server request.

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();
    }
}
musica
  • 1,373
  • 3
  • 15
  • 34
Raghav
  • 65
  • 1
  • 12

1 Answers1

4

you can set a tag to your request. It will be an identification for every request. After that, your request queue has a cancelAll method, it is require a tag.

//Before you add your request to the queue, set the tag, the tag can be a string, or sth like that.

yourRequest.setTag(tag);

After that, when you want to cancel your request :

requestQueue.cancelAll(tag);
Robert Banyai
  • 1,329
  • 12
  • 14
  • I am quite confuse.............in yourRequest.setTag(tag) and where to call requestQueue.cancelAll(tag) – Raghav Sep 22 '16 at 06:46