2012-05-12 15 views
0

更新:我發現最簡單的方法是使用AQuery如何使我的連接成爲AsyncTask連接

我需要讓我的HttpPost獲得另一個線程上的JSON數據,我不知道如何讓它們一起工作。我看着Painless Threading Blog,仍然無法讓它工作。

下面是我試圖對其進行解碼的原始代碼。

這是我第一次嘗試AsyncTasking,所以PLZ不要苛刻。日Thnx。

裏面我的OnCreate:

/** 
    * Connecting to MySQL using PHP and Populate the ListView 
    * ======================================================== 
    */ 
    mList = (ListView) findViewById(R.id.sidebar_list); 

    /** - http post for the list - */ 
    try //<--THIS TRY METHOD IS WHAT NEED TO BE ON A SEPERATE THREAD?? 
    { 
    HttpClient httpClient = new DefaultHttpClient(); 
    HttpPost httpPost = new HttpPost("http://192.168.1.34/xxxx/xxxxx_list.php"); 

    List<NameValuePair> nameValue = new ArrayList<NameValuePair>(); 
    httpPost.setEntity(new UrlEncodedFormEntity(nameValue)); 

    HttpResponse httpResponse = httpClient.execute(httpPost); 

    HttpEntity httpEntity = httpResponse.getEntity(); 

    is = httpEntity.getContent(); 

    } catch (Exception e) 
    { 
    // TODO handle e 
    Log.e("log_tag", "Error in HTTP connect" + e.toString()); 
    Toast.makeText(this, "HTTP Connection Error : " + e.toString(), Toast.LENGTH_LONG).show(); 
    } 

    // EVERYTHING BELOW HERE CAN BE ON THE UI THREAD??? 
    /** 
    * Convert response to string------------------------------------ 
    * ---------------------- 
    * */ 
    try 
    { 
    BufferedReader BufR = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); 
    sb = new StringBuilder(); 
    sb.append(BufR.readLine() + "\n"); 

    String line = "0"; 
    while ((line = BufR.readLine()) != null) 
    { 
    sb.append(line + "\n"); 
    } 
    is.close(); 
    result = sb.toString(); 
    } catch (Exception e) 
    { 
    // TODO handle e 
    Log.e("log_tag", "Error in convert to String" + e.toString()); 
    } 

    // paring data 
    int q_id; 
    String q_label; 
    String q_title; 
    String q_description; 
    String q_gotoURL; 

    try 
    { 
    jArray = new JSONArray(result); 
    JSONObject json_data = null; 
    for (int i = 0; i < jArray.length(); i++) 
    { 
    json_data = jArray.getJSONObject(i); 
    q_id = json_data.getInt("_ID"); 
    q_label = json_data.getString("label"); 
    q_title = json_data.getString("title"); 
    q_description = json_data.getString("description"); 
    q_gotoURL = json_data.getString("gotoURL"); 
    // mList.add(); 
    } 

    setupList(); 
    } catch (JSONException e1) 
    { 
    Toast.makeText(getBaseContext(), "No Data Found", Toast.LENGTH_LONG).show(); 
    } catch (ParseException e1) 
    { 
    e1.printStackTrace(); 
    } 

    }; 

回答

1

我想你可以嘗試這樣的事:

public class MyActivity extends Activity { 

// paring data 
int q_id; 
String q_label; 
String q_title; 
String q_description; 
String q_gotoURL; 
Context context; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    mList = (ListView) findViewById(R.id.sidebar_list); 
    context = getApplicationContext(); 
    new HttpTask().execute("http://192.168.1.34/xxxx/xxxxx_list.php"); 

} 
private class HttpTask extends AsyncTask<String, Void, String> { 


    protected String doInBackground(String... urls) { 
     try { 
      HttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(urls[0]); 

      List<NameValuePair> nameValue = new ArrayList<NameValuePair>(); 
      httpPost.setEntity(new UrlEncodedFormEntity(nameValue)); 

      HttpResponse httpResponse = httpClient.execute(httpPost); 

      HttpEntity httpEntity = httpResponse.getEntity(); 

      is = httpEntity.getContent(); 

      // Get result 
      BufferedReader BufR = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); 
      sb = new StringBuilder(); 
      sb.append(BufR.readLine() + "\n"); 

      String line = "0"; 
      while ((line = BufR.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
      is.close(); 
      result = sb.toString(); 

     } catch (Exception e) { 
      Toast.makeText(context, "HTTP Connection Error : " + e.toString(), Toast.LENGTH_LONG).show(); 
      return null; 
     } 
    } 

    protected void onPostExecute(String result) { 
     try { 
      if(result == null) 
       throw new Exception("result is null"); 
      jArray = new JSONArray(result); 
      JSONObject json_data = null; 
      for (int i = 0; i < jArray.length(); i++) { 
       json_data = jArray.getJSONObject(i); 
       q_id = json_data.getInt("_ID"); 
       q_label = json_data.getString("label"); 
       q_title = json_data.getString("title"); 
       q_description = json_data.getString("description"); 
       q_gotoURL = json_data.getString("gotoURL"); 
       // mList.add(); 
      } 
      //send message to handler to draw list 
      drawListHandler.sendEmptyMessage(0); 
     } catch (Exception e1) { 
      Toast.makeText(context, e1.getMessage(), Toast.LENGTH_LONG).show(); 
     } 
    } 
} 

Handler drawListHandler = new Handler(){ 
    /* (non-Javadoc) 
    * @see android.os.Handler#handleMessage(android.os.Message) 
    */ 
    @Override 
    public void handleMessage(Message msg) { 
     setupList(); 
    } 
}; 
} 
0

除了setupList()(假設更新一些ListView)和Toast,剩下的這些應該是doInBackground()。您希望儘可能少的代碼在主應用程序線程上。

+1

雖然也'mList =(ListView控件)findViewById(R.id.sidebar_list);'可以留在'的onCreate(...)'。 – Squonk