2013-07-20 47 views
0

這是我在這個網站上的第一篇文章,我有我的應用程序的問題,我無法找到我的應用程序停止的原因。我正在向Despegar發送一個請求以獲得這些國家的JSON,但發生這些。如果你能幫助我,我會非常棒。
這裏是我的代碼:Android:如何使用AsyncTasks的網絡服務

public class MainActivity extends Activity { 
final TextView txtResultado = (TextView) findViewById(R.id.txtResultado); 
String JSONRequest; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    new TareaConexion().execute("http://api.despegar.com/countries"); 

} 
class TareaConexion extends AsyncTask<String, Void, String>{ 

    protected void onPreExecute() { 
    } 

    protected String doInBackground(String... urls) { 
     httpHandler httphandler = new httpHandler(); 
     JSONRequest = httphandler.Post(urls[0]); 
     return JSONRequest; 
    } 

    protected void onProgressUpdate() {   
    } 

    protected void onPostExecute() { 
     txtResultado.setText(JSONRequest); 
    } 
} 

和類的HttpHandler:

public class httpHandler { 

public String Post (String PostURL) 
{ 
    try { 

     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost(PostURL); 

     HttpResponse resp = httpclient.execute(httppost); 
     HttpEntity ent = resp.getEntity(); 

     String Respuesta = EntityUtils.toString(ent); 

     return Respuesta; 
    } catch (Exception e) { 
     return "error"; 
    } 
} 
} 

有誰能夠找到它做我的應用程序停止的原因是什麼?我究竟做錯了什麼?

我是阿根廷人,所以如果我對lenguage,ajja犯了一個錯誤,請原諒我。由於

+2

登錄貓請。 – taxeeta

回答

1

試試這個代碼

MyAsyncTask extends AsyncTask<String, Void, HttpResponse> 
    { 
     @Override 
      protected HttpResponse doInBackground(String... param) 
      { 
       String url = param[0]; 

       HttpResponse response = null; 
       HttpClient httpclient = new DefaultHttpClient(); 
       httpclient.getParams().setParameter("http.connection-manager.timeout", 15000); 
       try { 

        if (type == Constants.TYPE_POST) 
        { 
         HttpPost httppost = new HttpPost(url); 
         response = httpclient.execute(httppost); 
        } 
        else if (type == Constants.TYPE_DELETE) 
        { 
         HttpDelete httpdelete = new HttpDelete(url); 
         response = httpclient.execute(httpdelete); 
        }   
        else 
        { 
         HttpGet httppost = new HttpGet(url); 
         response = httpclient.execute(httppost); 
        }  

       } catch (ClientProtocolException es) 
       { 
        Log.e("x" , es.getMessage()); 
       } catch (IOException e) 
       { 
        Log.e("aasx" , e.getMessage()); 
       } 
       return response; 

      } 

      @Override 
      protected void onPostExecute(HttpResponse response) 
      { 
       if (response != null) 
       { 
         JSONObject obj = new JSONObject(Utilities.convertStreamToString(response.getEntity().getContent())); 
        //Whatever you want to do   
       } 
      } 
     }