2014-01-10 103 views
0

這是我的代碼。我正在嘗試擴展AsyncTask,但它不起作用。這是我的代碼。 運行我的應用程序時顯示NetworkOnMainThread異常。我是android新手,我需要開發一個登錄系統。如何在此代碼中實現AsyncTask。

public class JSONParser extends AsyncTask<String,Void,JSONObject>{ 
    static InputStream mInputStream=null; 
    static JSONObject mJsonObject=null; 
    static String json=""; 
    String url=""; 
    List<NameValuePair> params=null; 

    public JSONParser() { 
    } 

    public JSONObject getJsonFromURL(String url,List<NameValuePair> params){ 
     url=this.url; 
     params=this.params; 
    return doInBackground(); 
    } 

    protected JSONObject doInBackground(String... params) { 
     try{ 
      DefaultHttpClient httpClient=new DefaultHttpClient(); 
      HttpPost httpPost=new HttpPost(url); 
      httpPost.setEntity(new UrlEncodedFormEntity(params)); 

      HttpResponse httpResponse=httpClient.execute(httpPost); 
      HttpEntity httpEntity=httpResponse.getEntity(); 
      mInputStream=httpEntity.getContent(); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     try{ 
      BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(mInputStream,"iso-8859-1"),8); 
      StringBuilder sb=new StringBuilder(); 
      String line= null; 
      while((line=bufferedReader.readLine())!=null){ 
       sb.append(line).append("\n"); 
      } 
      bufferedReader.close(); 
      json=sb.toString(); 
     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     try { 
      mJsonObject = new JSONObject(json); 
     } catch (JSONException e) { 
      Log.e("JSON Parser", "Error parsing data " + e.toString()); 
     } 
     return mJsonObject; 
     } 
} 

我不知道是不是正確的方法。 請幫幫我。 httpPost.setEntity(new UrlEncodedFormEntity(params)); 這條線顯示我的錯誤,不知道如何刪除它。廣東話申請的String []

+1

你究竟在哪裏擴展AsyncTask? –

+0

在我看來,你需要在AsyncTask中包裝你的getJsonFromURL函數來獲得結果。網絡活動無法在主線程上執行,這就是爲什麼使用Async任務。它在另一個線程中運行該活動。 –

+0

看到我的答案一些如何可以幫助你 – Developer

回答

1

創建回調接口

public interface CallBack { 
    void run(Object result); 
} 

RequestClient類

public class RequestClient extends AsyncTask<String, Void, String> { 
    Context context; 
    CallBack callBack; 

    public RequestClient(CallBack callBack) { 
     this.callBack = callBack; 
    } 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     //LoginPage.progressDialog.show(); 
    } 

    @Override 
    protected String doInBackground(String... params) { 
     String responseString = ""; 
     HttpClient client = null; 
     try { 
      client = new DefaultHttpClient(); 
      HttpGet get = new HttpGet(LoginPage.url); 
      client.getParams().setParameter("http.socket.timeout", 6000); 
      client.getParams().setParameter("http.connection.timeout", 6000); 
      HttpResponse responseGet = client.execute(get); 
      HttpEntity resEntityGet = responseGet.getEntity(); 
      if (resEntityGet != null) { 
       responseString = EntityUtils.toString(resEntityGet); 
       Log.i("GET RESPONSE", responseString.trim()); 
      } 
     } catch (Exception e) { 
      Log.d("ANDRO_ASYNC_ERROR", "Error is " + e.toString()); 
     } 
     Log.d("ANDRO_ASYNC_RESPONSE", responseString.trim()); 
     client.getConnectionManager().shutdown(); 
     return responseString.trim(); 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     // TODO Auto-generated method stub 
     super.onPostExecute(result); 
     callBack.run(result); 
     //LoginPage.progressDialog.dismiss(); 
    } 
} 

在登錄活動

RequestClient reqClient = new RequestClient(new CallBack() { 

      @Override 
      public void run(Object result) { 
       try { 
        AppResponse = (String) result; 

        String status =ValidateLoginStatus.checkLoginStatus(AppResponse); 
        Log.d("TAG Status recived", status); 

        if (status.equals("300")) { 
         saveInformation(userId, pass); 
         startingActivity(); 
        } else { 
         error.setText("Incorrect UserName or Password"); 
        } 
       } catch (Exception e) { 
        Log.e("TAG Exception Occured", 
          "Exception is " + e.getMessage()); 
       } 
      } 
     }); 
     reqClient.execute(url);