在onResume中获取数据加倍android中的数据?

时间:2016-06-15 03:45:45

标签: android

我有一个片段,其中onCreateView方法向服务器发送请求并获取一些数据。这工作正常但是当我在onResume中发送另一个请求时,它会使列表视图中的数据加倍。我该如何解决这个问题?

代码:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    m_Main = inflater.inflate(R.layout.deal_listing, container, false);//intialize mainLayout
    getDetails();// get deatail of user from sharedpreference......
    init();//initialize metho
    return m_Main;
}

private void getDetails() {// get details of user from shared preference...
    CLoginSessionManagement m_oSessionManagement = new CLoginSessionManagement(getActivity());// crating object of Login Session
    HashMap<String, String> user = m_oSessionManagement.getLoginDetails();// get String from Login Session
    m_szMobileNumber = user.get(CLoginSessionManagement.s_szKEY_MOBILE).trim();// getting password from saved preferences..........
    m_szEncryptedPassword = user.get(CLoginSessionManagement.s_szKEY_PASSWORD).trim();// getting mobile num from shared preferences...
    sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// increment of record count
    sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// increment of last count...

    s_oDataset = new ArrayList<>();// making object of Arraylist

    if (NetworkUtil.isConnected(getActivity())) {
        postDealListingDatatoServer();// here sending request in onCreate
    } else {

        Toast.makeText(getActivity(), "Please check internet connection !", Toast.LENGTH_LONG).show();
    }

}

@Override
public void onResume() {
    super.onResume();

    if (NetworkUtil.isConnected(getActivity())) {
        postDealListingDatatoServer();// here in on Resume send request which double data

    } else {

        Toast.makeText(getActivity(), "Please check internet connection !", Toast.LENGTH_LONG).show();
    }
}

private void init() {// initialize controls

    m_ProgressBar = (ProgressBar) m_Main.findViewById(R.id.progressBar1);// finding Id of progressview
    m_ProgressBar.setVisibility(View.GONE);// make profressView Invisible first time

    /*Swipe to refresh code*/
    mSwipeRefresh = (SwipeRefreshLayout) m_Main.findViewById(R.id.mainLayout);
    mSwipeRefresh.setColorSchemeResources(R.color.refresh_progress_1);

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

                m_ListView.removeFooterView(btnLoadMore);
                s_oDataset.clear();
                m_n_DeafalutLastCount = 0;
                sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// convert int value to string /////
                swipeData();


            } else {
                Toast.makeText(getActivity(), "Please check internet connection !", Toast.LENGTH_LONG).show();
                if (mSwipeRefresh.isRefreshing()) {

                    mSwipeRefresh.setRefreshing(false);
                }
            }
        }
    });
    m_n_FormImage = new int[]{// defining Images in Integer array
            R.drawable.amazon,
            R.drawable.whatsapp,
            R.drawable.zorpia,
            R.drawable.path,
            R.drawable.app_me,
            R.drawable.evernote,
            R.drawable.app_me};

    m_ListView = (ListView) m_Main.findViewById(R.id.dealList);// findind Id of Listview
    m_ListView.setFadingEdgeLength(0);
    m_ListView.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {


        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            if (firstVisibleItem == 0) {
                mSwipeRefresh.setEnabled(true);
            } else {
                mSwipeRefresh.setEnabled(false);
            }
        }
    });


}

    /*This is new changes in code ....using Volley instead of AsynkTask*/

/*This method send request to server for deallisting*/
// this method send request to server for deal list....
public void postDealListingDatatoServer() {
    try {
        String json;
        // 3. build jsonObject
        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
        // 4. convert JSONObject to JSON to String
        json = jsonObject.toString();// convert Json object to string

        System.out.println("Request:-" + json);
        m_Dialog = DialogUtils.showProgressDialog(getActivity(), "Please wait while loading deals...");
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, CServerAPI.m_DealListingURL, jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                System.out.println("Response:-" + response);
                m_Dialog.dismiss();
                try {
                    JSONArray posts = response.optJSONArray("dealList");// get Deal list in array from response
                    for (int i = 0; i < posts.length(); i++) {// loop for counting deals from server
                        JSONObject post = posts.getJSONObject(i);// counting deal based on index
                        item = new CDealAppDatastorage();// creating object of DealAppdata storage
                        item.setM_szHeaderText(post.getString("dealname"));// get deal name from response
                        item.setM_szsubHeaderText(post.getString("dealcode"));// get dealcode from response
                        item.setM_szDealValue(post.getString("dealvalue"));// get deal value from response
                        item.setM_n_Image(m_n_FormImage[i]);//set Image Index wise(Dummy)
                        s_oDataset.add(item);// add all items in ArrayList

                    }

                    // LoadMore button
                    btnLoadMore = new Button(getActivity());// creating button
                    btnLoadMore.setText("LOAD MORE DEALS");// set Text in Button
                    btnLoadMore.setBackgroundResource(R.drawable.button_boarder);// set Background Resource
                    btnLoadMore.setTypeface(Typeface.DEFAULT_BOLD);
                    btnLoadMore.setTextSize(14);
                    btnLoadMore.setTextColor(Color.WHITE);// set Color of button text
                    btnLoadMore.setGravity(Gravity.CENTER);// set Gravity of button text


                    if (!s_oDataset.isEmpty()) {// condition if data in arraylist is not empty
                        // Adding Load More button to lisview at bottom
                        m_ListView.addFooterView(btnLoadMore);// add footer in listview
                        m_oAdapter = new CDealAppListingAdapter(getActivity(), s_oDataset);// create adapter object and add arraylist to adapter
                        m_ListView.setAdapter(m_oAdapter);//adding adapter to recyclerview
                    } else {
                        btnLoadMore.setVisibility(View.GONE);// else Load buttonvisibility set to Gone
                    }
                    btnLoadMore.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {// load more button onclick listener
                            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
                                String itemscount = String.valueOf(m_ListView.getAdapter().getCount());
                                System.out.println("Toatal item:-" + itemscount);

                                sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// convert int value to string
                                sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// convert int value to string /////
                                loadmoreData();
                            } else {
                                Toast.makeText(getActivity(), "Please check internet connection !", Toast.LENGTH_LONG).show();
                            }
                        }
                    });
                    if (response.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {//server based conditions
                        CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "Connection Lost !", getActivity());
                    } else if (response.getString("resultdescription").equalsIgnoreCase("Deal List Not Found")) {// serevr based conditions .....
                        CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "No more deals available", getActivity());

                    } else if (response.getString("resultdescription").equalsIgnoreCase("Technical Failure")) {
                        CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "Technical Failure", getActivity());
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                System.out.println("Errror:-" + error);
                m_Dialog.dismiss();
                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 requestQueue = Volley.newRequestQueue(getActivity());
        requestQueue.add(jsonObjectRequest);
    } catch (JSONException e) {
        e.printStackTrace();
    }

}

3 个答案:

答案 0 :(得分:0)

请从正在调用postDealListingDatatoServer()的onCreateView中删除调用getDetails()。从onResume

调用getDetails()方法

你现在可以删除onResume()中的if-else块,只需从onResume调用getDetails()

另一种方法是,在调用postDealListingDatatoServer()之前清除s_oDataset,这样可以避免向列表中添加相同的数据

答案 1 :(得分:0)

onResume()总是在onCreate()之后调用,所以没有理由让它们做同样的事情。只需实现onResume来调用数据更新代码而不是onCreate()

答案 2 :(得分:0)

在向其添加新数据之前,您应该清除s_oDataset

你可以这样做:

JSONArray posts = response.optJSONArray("dealList");// get Deal list in array from response
s_oDataset.clear(); // clear the old values
for (int i = 0; i < posts.length(); i++) {// loop for counting deals from server
    JSONObject post = posts.getJSONObject(i);// counting deal based on index
    item = new CDealAppDatastorage();// creating object of DealAppdata storage
    item.setM_szHeaderText(post.getString("dealname"));// get deal name from response
    item.setM_szsubHeaderText(post.getString("dealcode"));// get dealcode from response
    item.setM_szDealValue(post.getString("dealvalue"));// get deal value from response
    item.setM_n_Image(m_n_FormImage[i]);//set Image Index wise(Dummy)
    s_oDataset.add(item);// add all items in ArrayList
}

要防止Button加倍,而不是:

m_ListView.addFooterView(btnLoadMore);

您可以检查ListView是否有FooterView并相应地创建Button

if(m_ListView.getFooterViewsCount() == 0) {
    btnLoadMore = new Button(getActivity());// creating button
    btnLoadMore.setText("LOAD MORE DEALS");// set Text in Button
    btnLoadMore.setBackgroundResource(R.drawable.button_boarder);// set Background Resource
    btnLoadMore.setTypeface(Typeface.DEFAULT_BOLD);
    btnLoadMore.setTextSize(14);
    btnLoadMore.setTextColor(Color.WHITE);// set Color of button text
    btnLoadMore.setGravity(Gravity.CENTER);
    m_ListView.addFooterView(btnLoadMore);
}