2016-04-28 12 views
1

私はMainActivityにアクションバーとリフレッシュボタンを含み、ActionbarとMainActivityに "Deal Listing"というフラグメントを追加します。listviewはURLを実行し、フラグメントの "Deal Listing"の一部とを更新します。 URLを実行して "Deal"フラグメントのListviewを更新します。fragment "Deal Listing"がMainActivityに追加されました。クリックしたときにDealFragmentのlistviewのコンテンツを更新したい場合や、 "deal"フラグメントがMainActivityに追加された場合"ディール" 断片listview refreshButon .How私はアンドロイドの別のアクティビティからAsynkTaskを呼び出す方法は?

はここDealListing断片のコードであることを行うのです: -

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", "[email protected]"); 
      // 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(); 
      } 
     } 

    } 
} 
+0

今私はSwipeRefreshLayoutを使用しています。使い方は簡単です.http://www.androidhive.info/2015/05/android-swipe-down-to-refresh-listview-tutorial/ –

+0

別のアクティビティでAsyncTaskを使用するには、現在のクラスから 'class CDealDataSent'を取り出す必要があります。 –

+0

画面が開いているときにurlを実行していますなぜ空白を表示してリフレッシュを使用しているのですか –

答えて

1

ActivityクラスまたはそのコンテキストをAsyncTaskに渡して、ダイアログの表示に関する問題を解決することができます。送信するURLとともに別のパラメータを組み込み、そのパラメータをContext変数に入れる必要があります。ダイアログが必要なときはいつでも、そのコンテキスト変数を使って表示します。

表示するコンテキストがダイアログに表示されていない場合は、間違いなく実行時エラーが発生します。

+0

code pls help me –

関連する問題