2012-10-26 57 views
0

我調試了我的程序,我注意到我wasent能夠在同一線程上運行網絡(我搜索這樣的錯誤2天,因爲在虛擬設備的應用程序工作沒有問題-.-)。所以現在我知道我該如何解決這個問題,但是我不知道如何給一些不是全部字符串的參數傳遞給doinBackground方法。Android AsyncTask方法,我不知道如何解決

我的方法需要一個url的方法,我可以在doInBackground方法中用params [0]和params [1]訪問afaik。但是,NameValuePairs List的最新功能如何在doInBackground方法中訪問?

非常感謝您的幫助:)

這是我的課:

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException; 
import java.util.List; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.client.params.ClientPNames; 
import org.apache.http.client.params.CookiePolicy; 
import org.apache.http.client.utils.URLEncodedUtils; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.os.AsyncTask; 
import android.util.Log; 

public class JSONParser extends AsyncTask<String, Void, JSONObject>{ 

    static InputStream is = null; 
    static JSONObject jObj = null; 
    static String json = ""; 

    // constructor 
    public JSONParser() { 

    } 

    // Funktion um JSON aus einer URL zu holen 
    // Es wird ein POST oder ein GET Request gesendet 
    public JSONObject makeHttpRequest(String url, String method, 
      List<NameValuePair> params) { 

     // HTTP Request erstellen 
     try { 

      // Überprüfen welche Request Methode benutzt werden soll 
      if(method == "POST"){ 
       DefaultHttpClient httpClient = new DefaultHttpClient(); 
       httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, 
         CookiePolicy.BROWSER_COMPATIBILITY); 
       HttpPost httpPost = new HttpPost(url); 
       httpPost.setEntity(new UrlEncodedFormEntity(params)); 

       HttpResponse httpResponse = httpClient.execute(httpPost); 
       HttpEntity httpEntity = httpResponse.getEntity(); 
       is = httpEntity.getContent(); 

      }else if(method == "GET"){ 
       DefaultHttpClient httpClient = new DefaultHttpClient(); 
       String paramString = URLEncodedUtils.format(params, "utf-8"); 
       url += "?" + paramString; 
       HttpGet httpGet = new HttpGet(url); 

       HttpResponse httpResponse = httpClient.execute(httpGet); 
       HttpEntity httpEntity = httpResponse.getEntity(); 
       is = httpEntity.getContent(); 
      }   

     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     //Stream in ein String umwandeln 
     try { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "iso-8859-1"), 8); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
      is.close(); 
      json = sb.toString(); 
     } catch (Exception e) { 
      Log.e("Fehler!", "Fehler mein umwandeln von Stream in String: " + e.toString()); 
     } 

     // JSON Object parsen 
     try { 
      jObj = new JSONObject(json); 
     } catch (JSONException e) { 
      Log.e("JSON Parser", "Error parsing data " + e.toString()); 
     } 

     // Das JSONObject zurückgeben 
     return jObj; 

    } 

    @Override 
    protected JSONObject doInBackground(String... params) { 
     // TODO Auto-generated method stub 
     return null; 
    } 
} 

回答

2

我不認爲你完全瞭解AsyncTasks的全部概念。當你想在後臺線程中運行一個操作時,你可以使用它們,這是完成這個任務的一個非常好的/靈活的方式。對我來說真的很好,在主線程中執行,所以一旦你的工作在doInBackground()中完成,它確實可以做一些強大的事情。不過請記住,因爲onPostExecute()確實在主線程上執行,所以您不希望在此執行任何網絡操作。

這裏是一個的AsyncTask的一個簡單的例子:

private class myAsyncTask extends AsyncTask<String, Void, Boolean> { 

    @Override 
    protected void onPreExecute() { 
     // before we start working 
    } 

    @Override 
    protected Boolean doInBackground(String... args) { 
     //do work in the background 
     return true; 
    } 

    @Override 
    protected void onPostExecute(Boolean success) { 
     // the work is done.. now what? 
    }  
} 

doInBackground()是你要去哪裏,在做大量的工作,所以我會盡力幫助你的基本結構,你想。我只是複製並粘貼您的代碼,我認爲它應該去,所以這是不是100%gauranteed,但希望這將有助於揭開序幕,你想做什麼:

private class JSONParser extends AsyncTask<String, Void, JSONObject> { 

    static InputStream is = null; 
    static JSONObject jObj = null; 
    static String json = ""; 

    // variables passed in: 
    String url; 
    String method; 
    List<NameValuePair> params; 

    // constructor 
    public JSONParser(String url, String method, 
     List<NameValuePair> params) { 
     this.url = url; 
     this.method = method; 
     this.params = params; 
    } 


    @Override 
    protected JSONObject doInBackground(String... args) { 
     try { 
      if(method == "POST"){ 
       DefaultHttpClient httpClient = new DefaultHttpClient(); 
       httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, 
         CookiePolicy.BROWSER_COMPATIBILITY); 
       HttpPost httpPost = new HttpPost(url); 
       httpPost.setEntity(new UrlEncodedFormEntity(params)); 

       HttpResponse httpResponse = httpClient.execute(httpPost); 
       HttpEntity httpEntity = httpResponse.getEntity(); 
       is = httpEntity.getContent(); 

      } else if(method == "GET"){ 
       DefaultHttpClient httpClient = new DefaultHttpClient(); 
       String paramString = URLEncodedUtils.format(params, "utf-8"); 
       url += "?" + paramString; 
       HttpGet httpGet = new HttpGet(url); 

       HttpResponse httpResponse = httpClient.execute(httpGet); 
       HttpEntity httpEntity = httpResponse.getEntity(); 
       is = httpEntity.getContent(); 
      } 
     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     try { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "iso-8859-1"), 8); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
      is.close(); 
      json = sb.toString(); 
     } catch (Exception e) { 
      Log.e("Fehler!", "Fehler mein umwandeln von Stream in String: " + e.toString()); 
     } 

     try { 
      jObj = new JSONObject(json); 
     } catch (JSONException e) { 
      Log.e("JSON Parser", "Error parsing data " + e.toString()); 
     } 

     return jObj; 
    } 

    @Override 
    protected void onPostExecute(JSONObject obj) { 
     // Now we have your JSONObject, play around with it. 
    }  
} 

編輯:

我忘了提到你也可以傳入args這是一個字符串數組。您只需創建指定參數和通過它,當你打電話給你的AsyncTask:

new JSONParser(url, method, params).execute(args); 

,您可以在doInBackground()

訪問ARGS這裏是AyncTask一些更多的信息:http://developer.android.com/reference/android/os/AsyncTask.html

+0

非常感謝你。它的工作:) – alexj

+0

很高興我能幫助! – burmat

相關問題