2013-08-01 44 views
0

我很新的android和我有asyncTask和線程的問題。 如何在此代碼中使用AsyncTask? 當我使用像這樣productIdList來null。這就是爲什麼我想使用AsyncTask。我認爲使用AsyncTask可以工作。使用線程和asyncTask

在此先感謝。

public ArrayList<String> getProductData() { 


    final ArrayList<String> productIdList = new ArrayList<String>(); 

    new Thread(new Runnable() { 

     public void run() { 
      HttpClient httpclient= new DefaultHttpClient(); 
      GeneralConstans GC = new GeneralConstans(); 
      // Products will be stated in memory 
      HttpPost httpget = new HttpPost(GC.UrlConstants); 
      HttpResponse response; 
      String result = null; 
      try { 

       HttpContext ctx = new BasicHttpContext(); 

       List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
         2); 
       httpget.setEntity(new UrlEncodedFormEntity(nameValuePairs, 
         "UTF-8")); 

       response = httpclient.execute(httpget, ctx); 
       HttpEntity resEntity = response.getEntity(); 

       if (resEntity != null) { 
        result = EntityUtils.toString(resEntity); 
        JSONArray arr = new JSONArray(result); 
        Gson gson = new Gson(); 
        if (arr.length() > 0) { 
         for (int j = 0; j < arr.length(); j++) { 
          Product p = gson.fromJson(arr.getString(j), 
            Product.class); 
          productIdList.add(p.toString()); 

         }      

        } 

       } 

      } catch (ClientProtocolException e) { 
       e.printStackTrace(); 
      } catch (SocketException e) { 
       /*if (checkAbortStatus(e.getMessage()) == true) { 
        handler.sendEmptyMessage(0); 
       }*/ 
      } catch (IOException e) { 
       /*if (checkAbortStatus(e.getMessage()) == true) { 
        handler.sendEmptyMessage(0); 
       }*/ 
       e.printStackTrace(); 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 


     } 

     private Handler handler = new Handler() { 
      @Override 
      public void handleMessage(Message msg) { 

       super.handleMessage(msg); 
      } 
     }; 

    }).start(); 
    return productIdList; 

回答

0

一個異步任務隱含移動的方法和命令,從主線程了,主線程應該運行的所有任務。

創建一個新的類,

public class <NAME OF CLASS> extends AsyncTask<Void, String, String> 

的延伸部分主要以擴展在一些參數(在C#繼承),這些參數與您打算利用3種overrided方法。

  1. onPreExecute - 這是一種預處事方法,我個人不需要它的代碼,我已經寫了(我還是新到Android自己)

  2. onDoInBackgound - 這是主要的AsyncTask的一部分,這就是你的所有方法都會去的地方,這就是所有邏輯都會發生的地方。這正是它在錫上所說的,它在另一個線程的背景中做了所有事情。

  3. onPostExecute - 當onDoInBackground完成後它將運行OnPostExecute方法,我通常對onDoInBackgroun方法,確保其發展到onPostExecute,因爲我有時會發現沒有它它沒有相當進步的字符串返回。

然後在postExecute方法,你告訴它你想做的事,一旦所有的邏輯是做什麼工作,例如,你可以有主線程上的監聽中,你從AysncTask即listener.onSuccess調用監聽器(結果)在postExecute方法,這將返回到原始線程。

希望這會有所幫助