2016-03-18 68 views
1

UI我已經從那裏我執行AsynkTask類是獨立類的類CDealListing,我要的是更新類CDealListing的UI上AsynkTask類onPOST等方法.kindly幫助我.... 。如何更新來自不同AsynkTask類

這裏是我的類CDealListing

public class CDealAppListing extends Fragment { 
public static String m_DealListingURL = "http://192.166.0.110:8080/ireward/rest/json/metallica/getDealListInJSON"; 
public static String s_szresult = " "; 
public static RecyclerView m_RecyclerView; 
public static CDealAppListingAdapter m_oAdapter; 
public static CDealAppDatastorage item; 
public ArrayList<CDealAppDatastorage> s_oDataset; 
public int[] m_n_FormImage; 
public View m_Main; 
public CRegistrationSessionManagement m_oSessionManagement; 
public String m_szMobileNumber, m_szEncryptedPassword; 
public LinearLayoutManager mLayoutManager; 
public AppCompatButton m_showMore; 
public ProgressBar mProgressBar; 
public int m_n_DefaultRecordCount = 5;// intiallly record count is 5. 
public int m_n_DeafalutLastCount = 0;//initally lastcount is 0. 

public String sz_RecordCount, sz_LastCount; 
//declare boolean 
private CJsonsResponse m_oJsonsResponse; 


@Nullable 
@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    m_Main = inflater.inflate(R.layout.deal_app_listing, container, false);//intialize mainLayout 
    new CDealDataSent().execute(m_DealListingURL); 
    init();//initialize method 
    implementScroll(); 
    return m_Main; 
} 

public void init() { 
    mProgressBar = (ProgressBar) m_Main.findViewById(R.id.progressBar1); 
    mProgressBar.setVisibility(View.GONE); 

    m_showMore = (AppCompatButton) m_Main.findViewById(R.id.show_more); 
    m_showMore.setBackgroundColor(Color.TRANSPARENT); 
    m_showMore.setVisibility(View.GONE); 
    // Getting the string array from strings.xml 
    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_RecyclerView = (RecyclerView) m_Main.findViewById(R.id.my_recycler_view);//finding id of recyclerview 
    m_RecyclerView.setItemAnimator(new DefaultItemAnimator());//setting default animation to recyclerview 
    m_RecyclerView.setHasFixedSize(true);//fixing size of recyclerview 
    mLayoutManager = new LinearLayoutManager(getActivity()); 
    m_RecyclerView.setLayoutManager(mLayoutManager);//showing odata vertically to user. 
    m_oSessionManagement = new CRegistrationSessionManagement(getActivity()); 
    HashMap<String, String> user = m_oSessionManagement.getRegistrationDetails(); 
    m_szEncryptedPassword = user.get(m_oSessionManagement.s_szKEY_PASSWORD); 
    m_szMobileNumber = user.get(m_oSessionManagement.s_szKEY_MOBILENUMBER); 

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

public void implementScroll() { 
    m_RecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { 
     @Override 
     public void onScrollStateChanged(RecyclerView recyclerView, int newState) { 
      super.onScrollStateChanged(recyclerView, newState); 
      if (newState == RecyclerView.SCROLL_STATE_IDLE){ 

      } 
     } 

     @Override 
     public void onScrolled(RecyclerView recyclerView, int dx, int dy) { 
      super.onScrolled(recyclerView, dx, dy); 
      if (dy > 0) { 

       m_showMore.setVisibility(View.VISIBLE); 
       m_showMore.setOnClickListener(new View.OnClickListener() { 
        @Override 
        public void onClick(View v) { 
         //change boolean value 
         m_showMore.setVisibility(View.GONE); 
         m_n_DefaultRecordCount = m_n_DefaultRecordCount + 5; 
         m_n_DeafalutLastCount = m_n_DeafalutLastCount + 5; 

         sz_RecordCount = String.valueOf(m_n_DefaultRecordCount); 
         sz_LastCount = String.valueOf(m_n_DeafalutLastCount); 
         new DealNext().execute(m_DealListingURL); 
        } 
       }); 
      } else { 
       m_showMore.setVisibility(View.GONE); 
      } 
     } 
    }); 
} 
//sending deal data to retreive response from server 
public String DealListing(String url, CRegistrationDataStorage login) { 
    InputStream inputStream = null; 
    m_oJsonsResponse = new CJsonsResponse(); 
    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(); 
     // 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 
      if (inputStream != null) 
       s_szresult = m_oJsonsResponse.convertInputStreamToString(inputStream); 
      //String resp_body = 
      EntityUtils.toString(httpResponse.getEntity()); 
     } else 
      s_szresult = "Did not work!"; 
    } catch (Exception e) { 
     Log.d("InputStream", e.getLocalizedMessage()); 
    } 
    System.out.println("resul.....:" + s_szresult); 
    // 11. return s_szResult 
    return s_szresult; 
} 

的代碼,這裏是我的asynkTask類

/ sending deal data to server and retreive response...... 
class CDealDataSent extends AsyncTask<String, Void, String> { 
    public JSONObject m_oResponseobject; 
    public ProgressDialog m_PDialog; 
    public CRegistrationDataStorage oRegisterStorage; 
    public CDealAppDatastorage item; 

    //  @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     m_PDialog = new ProgressDialog(getActivity()); 
     m_PDialog.setMessage("Please wait while Loading Deals..."); 
     m_PDialog.setCancelable(false); 
     m_PDialog.show(); 
    } 
    @Override 
    protected String doInBackground(String... urls) { 
     return DealListing(urls[0], oRegisterStorage);// sending data to server... 

    } 
    // onPostExecute displays the results of the AsyncTask. 
    @Override 
    protected void onPostExecute(String result) { 

     m_PDialog.dismiss(); 
     try { 
      m_oResponseobject = new JSONObject(result);// getting response from server 
      final JSONArray posts = m_oResponseobject.optJSONArray("dealList"); 

      s_oDataset = new ArrayList<CDealAppDatastorage>(); 
      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_n_Image(m_n_FormImage[i]); 
       s_oDataset.add(item); 

      } 
      getResponse(); 

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

    public void getResponse() throws JSONException { 
     if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Transaction Successful")) { 

      m_oAdapter = new CDealAppListingAdapter(s_oDataset);//creating object of adapter and addd setting odata to adapter for use. 
      m_RecyclerView.setAdapter(m_oAdapter);//adding adapter to recyclerview 
     } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) { 
      Toast.makeText(getActivity(), "Connection not avaliable", Toast.LENGTH_SHORT).show(); 
     }else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Deal List Not Found")){ 
      Toast.makeText(getActivity(),"No More Deals",Toast.LENGTH_SHORT).show(); 
     } 
     System.out.println("agentCode...." + m_szMobileNumber); 
     System.out.println("password...." + m_szEncryptedPassword); 
     System.out.println("record////" + sz_RecordCount); 
     System.out.println("last:........" + sz_LastCount); 
    } 

} 

在asynkTask類獲得CLAS的響應方法更新UI小號CDealListing

回答

0

有3種方式

  1. 呼叫在onPostExecute()
  2. 使用EventBus庫您FragmentonPostExecute()
  3. 使用BroadcastReceiver一些方法通過事件您Fragment
0

一種方法是聲明偵聽器接口並將該接口的實例(或可能是Runnable)傳遞到AsyncTask的構造函數中。

在您的片段代碼:

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    ...   
    new CDealDataSent(new Runnable() { 
     @Override 
     public void run() { 
      // perform update UI code here 
     } 
    }).execute(m_DealListingURL); 
    ... 
} 

在你的AsyncTask代碼:

class CDealDataSent extends AsyncTask<String, Void, String> { 
    private final Runnable mOnPostExecuteRunnable; 
    CDealDataSent(Runnable onPostExecuteRunnable) { 
     mOnPostExecuteRunnable = onPostExecuteRunnable; 
    } 

    ... 

    @Override 
    protected void onPostExecute(String result) { 
     ... 
     if (mPostExecuteRunnable != null) { 
      mPostExecuteRunnable.run(); 
     } 
     ... 
    } 
} 

您還可以使用的AsyncTask的一個匿名子類,從你的片段和覆蓋onPostExecute():

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    ...   
    new CDealDataSent() { 
     @Override 
     protected void onPostExecute(String result) { 
      super.onPostExecute(result); // be sure to call super first to do normal processing 
      ... // update your UI here 
     } 
    }.execute(m_DealListingURL); 
    ... 
} 

注意,這兩種解決方案都傾向於活動/片段泄漏,如果你不關心因爲Runnable /匿名子類的父類保留爲隱式引用。如果用戶退出onDestroy()中的活動,請務必取消任何未完成的AsyncTasks。

您可以通過靜態嵌套類來緩解任何潛在的泄漏問題,或者可以將Handler實例傳遞給AsyncTask,以便在onPostExecute()完成其作業時發送消息。有關此問題的討論,請參閱What's the correct way to implement AsyncTask? static or non static nested class?

+0

,但我怎樣才能使progressdialog可見 –