1

I have a MainActivity contain a Action bar and a refresh button in action bar and MainActivity add a Fragment called "Deal Listing" contain listview which execute Url and Update some Listview of fragment "Deal Listing" and a Fragment "Deal" which also execute URL and update Listview of "Deal" fragment.what I want when fragment "Deal Listing" added to MainActivity I want to refresh content of listview of DealFragment on click refreshButon and when "deal" fragment added to MainActivity I want to refresh content of "Deal" fragment listview refreshButon .How do I do that

Here is code of DealListing Fragment:-

  private void init() {
        m_LoadMoreProgressView = (CircularProgressView) m_Main.findViewById(R.id.progressBar1);
        m_LoadMoreProgressView.setVisibility(View.GONE);

        m_n_FormImage = new int[]{
                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);


        sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// increment of record count
        sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// increment of last count...

    }


    @SuppressWarnings("deprecation")
    private String DealListing(String url) {
        InputStream inputStream;
        try {
            // 1. create HttpClient
            HttpClient httpclient = new DefaultHttpClient();
            // 2. make POST request to the given URL
            HttpPost httpPost = new HttpPost(url);
            String json;
            // 3. build jsonObject
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("agentCode", m_szMobileNumber);
            jsonObject.put("pin", m_szEncryptedPassword);
            jsonObject.put("recordcount", sz_RecordCount);
            jsonObject.put("lastcountvalue", sz_LastCount);
            //jsonObject.put("emailId", "nirajk1190@gmail.com");
            // 4. convert JSONObject to JSON to String
            json = jsonObject.toString();
            System.out.println("Jsons:-" + json);
            // 5. set json to StringEntity
            StringEntity se = new StringEntity(json);
            // 6. set httpPost Entity
            httpPost.setEntity(se);
            // 7. Set some headers to inform server about the type of the content
            httpPost.setHeader("Content-type", "application/json");
            // 8. Execute POST request to the given URL
            HttpResponse httpResponse = httpclient.execute(httpPost);
            HttpEntity entity = httpResponse.getEntity();
            // 9. receive response as inputStream
            inputStream = entity.getContent();
            System.out.println("InputStream....:" + inputStream.toString());
            System.out.println("Response....:" + httpResponse.toString());

            StatusLine statusLine = httpResponse.getStatusLine();
            System.out.println("statusLine......:" + statusLine.toString());
            ////Log.d("resp_body", resp_body.toString());
            int statusCode = statusLine.getStatusCode();
            // 10. convert inputstream to string
            if (statusCode == 200) {
                // 10. convert inputstream to string
                s_szresult = CJsonsResponse.convertInputStreamToString(inputStream);
                //String resp_body =
            } else
                s_szresult = "Did not work!";
        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }
        System.out.println("resul.....:" + s_szresult);
        System.out.println("pin:" + m_szEncryptedPassword);
        System.out.println("recordCount:" + sz_RecordCount);
        System.out.println("LastCount:" + sz_LastCount);
        // 11. return s_szResult
        return s_szresult;
    }

    @SuppressWarnings("StatementWithEmptyBody")
    private void getResponse() throws JSONException {// getting response from serevr ..................
        if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Transaction Successful")) {// server based condition


        } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {//server based conditions
            CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "Connection Lost !", getActivity());
        } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Deal List Not Found")) {// serevr based conditions .....
            CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "No more deals available", getActivity());

        }
    }

    //  sending deal data to server and retreive response......
    class CDealDataSent extends AsyncTask<String, Void, String> {
        public CDealAppDatastorage item;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            m_ProgressView.setVisibility(View.VISIBLE);
        }

        @Override
        protected String doInBackground(String... urls) {
            return DealListing(urls[0]);// sending data to server...

        }

        // onPostExecute displays the results of the AsyncTask.
        @SuppressWarnings("deprecation")
        @SuppressLint("SetTextI18n")
        @Override
        protected void onPostExecute(final String result) {

            m_ProgressView.setVisibility(View.GONE);
            try {
                m_oResponseobject = new JSONObject(result);// getting response from server
                JSONArray posts = m_oResponseobject.optJSONArray("dealList");


                for (int i = 0; i < posts.length(); i++) {
                    JSONObject post = posts.getJSONObject(i);
                    item = new CDealAppDatastorage();
                    item.setM_szHeaderText(post.getString("dealname"));
                    item.setM_szsubHeaderText(post.getString("dealcode"));
                    item.setM_szDealValue(post.getString("dealvalue"));
                    item.setM_n_Image(m_n_FormImage[i]);
                    s_oDataset.add(item);

                }

                // LoadMore button
                Button btnLoadMore = new Button(getActivity());
                btnLoadMore.setText("LOAD MORE DEALS");
                btnLoadMore.setBackgroundResource(R.drawable.button_boarder);
                btnLoadMore.setTextAppearance(getActivity(), android.R.style.TextAppearance_DeviceDefault_Small);
                btnLoadMore.setTextColor(Color.WHITE);
                btnLoadMore.setGravity(Gravity.CENTER);
                if (!s_oDataset.isEmpty()) {
                    // Adding Load More button to lisview at bottom
                    m_ListView.addFooterView(btnLoadMore);
                    m_oAdapter = new CDealAppListingAdapter(getActivity(), s_oDataset);// create adapter object and add arraylist to adapter
                    m_ListView.setAdapter(m_oAdapter);//adding adapter to recyclerview
                    m_oAdapter.notifyDataSetChanged();
                } else {
                    btnLoadMore.setVisibility(View.GONE);
                }


                btnLoadMore.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        m_n_DefaultRecordCount = 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 /////
                        new DealNext().execute(m_DealListingURL);// POST DATA TO SERVER TO LOAD MORE DATA......
                    }
                });

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


        }
    }

    //  sending data and receive reponse on second hit T LOAD MORE DATA  when show more Btn  clicked..............
    private class DealNext extends AsyncTask<String, Void, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            m_LoadMoreProgressView.setVisibility(View.VISIBLE);// SHOW PROGRESS BAR
        }

        @Override
        protected String doInBackground(String... urls) {
            //My Background tasks are written here
            synchronized (this) {
                return DealListing(urls[0]);// POST DATA TO SERVER
            }
        }

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

            m_LoadMoreProgressView.setVisibility(View.GONE);// DISMISS PROGRESS BAR..........
            try {
                m_oResponseobject = new JSONObject(result);// getting response from server
                final JSONArray posts = m_oResponseobject.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);
                    }

                }
                // get listview current position - used to maintain scroll position
                int currentPosition = m_ListView.getFirstVisiblePosition();
                m_oAdapter = new CDealAppListingAdapter(getActivity(), s_oDataset);
                m_ListView.setAdapter(m_oAdapter);
                // Setting new scroll position
                m_ListView.setSelectionFromTop(currentPosition + 1, 0);

                getResponse();// getting response from server.....and also here response based logics...


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

    }
}
Aditya Vyas-Lakhan
  • 13,007
  • 15
  • 58
  • 92
Raghvender Kumar
  • 125
  • 3
  • 11
  • Now this days i am using SwipeRefreshLayout it's easy to use just check it.http://www.androidhive.info/2015/05/android-swipe-down-to-refresh-listview-tutorial/ – Arpit Patel Apr 28 '16 at 04:44
  • If you want to use the AsyncTask in another Activity, you'll need to pull `class CDealDataSent` out of the current class. – OneCricketeer Apr 28 '16 at 04:46
  • I am executing url sometime when Screen is open show blank that why I am using refresh – Raghvender Kumar Apr 28 '16 at 04:46
  • how to pull solution pls – Raghvender Kumar Apr 28 '16 at 04:46
  • Sadly, with the amount of code you've mixed together between the AsyncTask and the Activity variables, it would be difficult. Since you are dealing with JSON, I would recommend you consider using the Retrofit+Gson libraries to handle all the JSON and HTTP stuff for you. – OneCricketeer Apr 28 '16 at 04:50
  • ok.. if I execute Url in oncreate and set intially 10 response in listview and listview has a load more button when user click on load more it will again execute url and fetch 10 more details .How I refresh when on click refresh button – Raghvender Kumar Apr 28 '16 at 05:04
  • 1
    you can find a good example [here](http://stackoverflow.com/questions/16545022/call-asynctask-from-another-class) your post seems duplicate of this question. so first search than ask. – Devendra Singh Apr 28 '16 at 05:06
  • Ok I have a Fragment called DealMainListing which contain two tab is that posible to add Toolbar with navigation drawer in that – Raghvender Kumar Apr 28 '16 at 05:16

1 Answers1

1

If you can somehow pass the Activity class or its context to the AsyncTask that will solve your issue for showing dialog. You would need to include another parameter together with the URL you are sending and put that parameter in a Context variable. And then whenever you need the dialog you use that context variable to show it.

If the dialog does not have a Context from which to show it will definitely run into runtime errors.

Devendra Singh
  • 2,899
  • 4
  • 26
  • 47