2013-04-16 51 views
1

我在android中創建應用程序,我有登錄註銷活動,Multilistview活動哪些數據來自其他Web服務。這裏的問題是,當從登錄活動調用webservice時,我得到錯誤networkonmainthreadexception然後我搜索了有關該異常的護目鏡,有人說在堆棧溢出使用AsyncTask在你的代碼分離線程和我在我的代碼中執行asynctask但不工作。我完全混淆瞭如何使用asynctask,我想在下面的代碼中添加asynctask。我提供的代碼沒有asynctask,我做了。任何人都可以幫助我在調用webservice時如何正確使用asynctask。android:如何在Rest Web服務中使用asyncTask?

以下是編輯文本通話功能

UserFunctions userFun = new UserFunctions(); 

     if ((username.trim().length() > 0)&&(userpsw.trim().length() > 0)) { 

      JSONObject json = userFun.loginUser(username, userpsw); 
      . 
         . 
         . 

以下是功能類

public JSONObject loginUser(String userEmail, String userPsw) { 

     List<NameValuePair> params = new ArrayList<NameValuePair>(); 
     params.add(new BasicNameValuePair("tag", login_tag)); 
     params.add(new BasicNameValuePair("email", userEmail)); 
     params.add(new BasicNameValuePair("password", userPsw)); 
     JSONObject json = jsonParser.getJsondataFromUrl(params); 
     //Log.d("tag", json.toString()); 
     return json; 
    } 

下面是實際WebService類提前

public void getJsondataFromUrl(List<NameValuePair> params) { 

    { 
     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     HttpPost httpPost = new HttpPost(url); 
     httpPost.setEntity(new UrlEncodedFormEntity(params)); 

     HttpResponse httpResp = httpClient.execute(httpPost); 
     HttpEntity httpEntity = httpResp.getEntity(); 
     inStream = httpEntity.getContent(); 
     //Log.d(tag, inStream.toString()); 
    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    try { 
     BufferedReader bufferReader = new BufferedReader(new InputStreamReader 
       (inStream, "iso-8859-1"), 8); 
     StringBuilder strBuilder = new StringBuilder(); 
     String line = null; 
     while ((line = bufferReader.readLine()) != null) { 
      strBuilder.append(line + "n"); 
     } 
     inStream.close(); 
     json = strBuilder.toString(); 
     //Log.d("JSON", json); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    // try parse the string to a JSON object 
    try { 
     jsonObj = new JSONObject(json); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 

    return jsonObj;*/ 
} 

由於獲取數據

回答

2

創建一個從AsyncTask繼承的類。在doInBackground中調用您的網絡代碼並返回一個POJO。在postExecute中,使用此POJO更新您的視圖。按照AsyncTask方法的簽名來理解如何用泛型鍵入你的子類。

你也應該考慮這個線程:https://stackoverflow.com/a/13147992/693752 AsyncTask並不是真正在Android上創建網絡請求的最佳工具。

+0

感謝Snicolas很好的信息。我還閱讀了關於robospice的鏈接。 – Nilesh

2
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    requestWindowFeature(Window.FEATURE_NO_TITLE); 
    setContentView(R.layout.login); 
    context=this; 


    Log.v(TAG+"onCreate", "OnCreate Called"); 
    username = (EditText)findViewById(R.id.editText_user); 
    password = (EditText)findViewById(R.id.editText_psw); 

    btngo = (ImageButton)findViewById(R.id.imageButton_go); 
    btngo.setOnClickListener(this); 



} 
@Override 
public void onClick(View v) { 
    Log.v(TAG+"onClick", "onClick Called"); 
    if(v== btngo) 
    { 
     user=username.getText().toString().trim(); 
     psw=password.getText().toString().trim(); 


       dialog = ProgressDialog.show(context, "", "Please! Wait...",true); 

       GetResult result = new GetResult(); 
       result.execute(); 

     } 
    } 

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

    @Override 
    protected String doInBackground(String... urls) { 
     Log.v(TAG + ".doInBackground", "doInBackground method call"); 
     String response1 = null; 

      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost("url"); 
      // Log.d("response", "WORKING"); 
      try { 

       List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
       nameValuePairs.add(new BasicNameValuePair("webservice", "1")); 
       nameValuePairs.add(new BasicNameValuePair("Email_ID", user)); 
       nameValuePairs.add(new BasicNameValuePair("Password",psw)); 

       httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
       HttpResponse response = httpclient.execute(httppost); 
       InputStream is = response.getEntity().getContent(); 
       WebHelper webHelper = new WebHelper(); 
       response1 = webHelper.convertStreamToString(is); 
       Log.v(TAG+".doInBackground", "json response is:" + response1); 

     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 


     return response1; 


    } 

    @Override 
    protected void onPostExecute(String result) { 

     Log.v(TAG + ".onPostExecute", "onPostExecute method call"); 
     dialog.dismiss(); 
     Log.v(TAG+".onPostExecute", "json response is:" + result); 

     /* Intent intent= new Intent(LoginActivity.this, ChoiceExamActivity.class); 
     startActivity(intent); 
     */ 

     if(result!=null){ 

      try { 
       //JSONTokener tokener = new JSONTokener(result); 
       JSONObject resultObjct = new JSONObject(result); 
       String user_id=resultObjct.getString("User_ID"); 

       if(user_id.equalsIgnoreCase("0")) 
       { 
        ExamUtil.showAlert(LoginActivity.this,"Incorrect User name or password"); 
       } 
       else 
       { 
       String firstname = resultObjct.getString("First_Name"); 
       Log.v(TAG+".onPostExecute", "user id is:" + user_id); 
       Log.v(TAG+".onPostExecute", "firstname is:" + firstname); 



       Intent intent= new Intent(LoginActivity.this, ChoiceExamActivity.class); 
       startActivity(intent); 

       } 

       } catch (JSONException e) { 
       e.printStackTrace(); 
       } 
       catch (Exception e) { 
       e.printStackTrace(); 
       } 
      } 

     else{ 

       ExamUtil.showAlert(LoginActivity.this,"We have some problem in processing request, try again."); 
      } 




    } 
} 
} 
+0

謝謝sunil對我來說很好的解決方案,但我有另一個活動,也可以使用其餘的web服務我的問題是,我可以在每個活動中寫asynctask。 – Nilesh

+0

是的,你可以在每個活動中使用asynctask。 –