2013-07-30 107 views
1

我有以下問題。在我得到了android.os.NetworkOnMainThreadException之後,我去尋找一個解決方案,並且看起來,AsyncTask是處理這個問題的最好方法。如何使用AsyncTask,我必須在哪裏放置代碼行?

但是,當我讀了幾頁後,我仍然不知道如何實現AsyncTask。

首先,我會告訴你我知道我的問題,至今在一起:

在這裏,我會嘗試調用web服務。

package net.frontend.androidapp.statusrequest; 

import org.ksoap2.SoapEnvelope; 
import org.ksoap2.serialization.SoapObject; 
import org.ksoap2.serialization.SoapSerializationEnvelope; 
import org.ksoap2.transport.HttpTransportSE; 

import android.app.Activity; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.View; 
import android.widget.EditText; 
import android.widget.TextView; 

public class PurchaseRequisitionRequest extends Activity { 


    private String METHOD_NAME = "parser" ; 
    private String NAMESPACE = "http://statusrequest.androidapp.webservice.backend.net"; 
    private String SOAP_ACTION = NAMESPACE + METHOD_NAME; 
    private static final String URL = "http://10.35.105.31:8080/SAPInterfaceWebservice/services/XMLTransfromer?wsdl"; 


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

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.purchase_requisition_request, menu); 
     return true; 
    } 

    public void checkStatus (View view) { 



     try 
     { 
     SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); 
     EditText edit = (EditText) findViewById (R.id.prRequest); 
      String s= edit.getText().toString(); 
      long lineNr=Long.parseLong(s); 
     request.addProperty("lineNr", lineNr); 

     SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 
     envelope.dotNet = true; 
     envelope.setOutputSoapObject(request); 
     HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); 
     androidHttpTransport.call(SOAP_ACTION,envelope); 
     Object result = envelope.getResponse(); 
     String hString = result.toString(); 
     String[] details = hString.split(","); 

     ((TextView) findViewById (R.id.request_detail1)).setText("PR_Number: " +details[0].substring(1)); 
     ((TextView) findViewById (R.id.request_detail2)).setText("Result1: " +details[1]); 
     ((TextView) findViewById (R.id.request_detail3)).setText("Result2: " +details[2]); 
     ((TextView) findViewById (R.id.request_detail4)).setText("Result3: " +details[3]); 
     ((TextView) findViewById (R.id.request_detail5)).setText("Entered Number: " + lineNr); 
     } catch (Exception E) { 
     E.printStackTrace(); 
     ((TextView) findViewById (R.id.request_detail1)).setText("ERROR: " + E.getClass().getName() + " : " + E.getMessage()); 
     } 

    } 
} 

據我瞭解,我已經把這裏的唯一事情就是

MyClassName().execute(A,B,C);

對我的CheckStatus方法。 (當按下按鈕時調用此方法)

那麼這條線在哪裏?

私有類MyClassName延伸的AsyncTask

我現在創建一個新的類,給它一個好聽的名字,然後把這個線旁

保護龍doInBackground(參數... PARAMS )

然後我的代碼部分CheckStatus

這是正確的嗎?

接下來的事情是,我不知道,哪些參數,所以你必須給予執行(a,b,c)調用?

有人可以給我一些代碼示例,使用我的代碼?我真的很感激。 我很抱歉問這麼基本的問題,但我不明白它是如何工作的。

非常感謝您的幫助!

+1

閱讀本機制的文檔的http://開發商.android.com/reference/android/os/AsyncTask.html – Shruti

+0

[API參考](http://developer.android.com/reference/android/os/AsyncTask.html)是您處理這類問題的第一站。如果文檔不符合要求,請使用您最喜愛的搜索引擎找到一些教程或示例。 –

回答

3
public class PurchaseRequisitionRequest extends Activity { 


     private String METHOD_NAME = "parser" ; 
     private String NAMESPACE = "http://statusrequest.androidapp.webservice.backend.net"; 
     private String SOAP_ACTION = NAMESPACE + METHOD_NAME; 
     private static final String URL = "http://10.35.105.31:8080/SAPInterfaceWebservice/services/XMLTransfromer?wsdl"; 

     String Error_Msg = ""; 

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

      new asyncTask().execute(); 

     } 

     @Override 
     public boolean onCreateOptionsMenu(Menu menu) { 
      // Inflate the menu; this adds items to the action bar if it is present. 
      getMenuInflater().inflate(R.menu.purchase_requisition_request, menu); 
      return true; 
     } 

     private class asyncTask extends AsyncTask<Void, Void, Boolean> 
     { 
      ProgressDialog pd; 

      protected void onPreExecute() 
      { 
       pd.setTitle("Please Wait..."); 
       pd.setMessage("Saving..."); 
       pd.setCancelable(false); 
       pd.show(); 
      } 
      protected void onPostExecute(Boolean result) 
      { 
       if(result) 
       { 
        ((TextView) findViewById (R.id.request_detail1)).setText("PR_Number: " +details[0].substring(1)); 
        ((TextView) findViewById (R.id.request_detail2)).setText("Result1: " +details[1]); 
        ((TextView) findViewById (R.id.request_detail3)).setText("Result2: " +details[2]); 
        ((TextView) findViewById (R.id.request_detail4)).setText("Result3: " +details[3]); 
        ((TextView) findViewById (R.id.request_detail5)).setText("Entered Number: " + lineNr); 
       } 
       else 
       { 
        ((TextView) findViewById (R.id.request_detail1)).setText(Error_Msg); 
       } 
       if(pd.isShowing()) pd.dismiss(); 
      } 

      @Override 
      protected Boolean doInBackground(Void... params) 
      { 
       try 
       { 
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); 
        EditText edit = (EditText) findViewById (R.id.prRequest); 
        String s= edit.getText().toString(); 
        long lineNr=Long.parseLong(s); 
        request.addProperty("lineNr", lineNr); 

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 
        envelope.dotNet = true; 
        envelope.setOutputSoapObject(request); 
        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); 
        androidHttpTransport.call(SOAP_ACTION,envelope); 
        Object result = envelope.getResponse(); 
        String hString = result.toString(); 
        String[] details = hString.split(","); 

        Error_Msg = hString; 

       } catch (Exception E) 
       { 
        E.printStackTrace(); 
        Error_Msg = "ERROR: " + E.getClass().getName() + " : " + E.getMessage(); 
       } 
       return true; 
      } 
      else 
      { 
       return false;    
      } 
     } 
    } 

} 
0

http://developer.android.com/reference/android/os/AsyncTask.html

異步任務是由3種一般類型,稱爲PARAMS,進展和結果,以及4個步驟,稱爲onPreExecute,doInBackground,onProgressUpdate和onPostExecute定義。

的AsyncTask的一般類型:

Params, the type of the parameters sent to the task upon execution. 
Progress, the type of the progress units published during the background computation. 
Result, the type of the result of the background computation. 
1

首先,來看看here,然後這個例子here

所謂的「慢」代碼在新創建的類的doInBackground()部分。

+0

謝謝,不知何故,我設法錯過了這個例子,儘管我試圖找到一個例子。我看了一下developer.android頁面,但我不明白。但現在我覺得我明白了。 –

+0

不客氣:) – g00dy

1

爲什麼不使用Google Volley(在今年的I/O中引入)。 它有一個簡單的網絡和遠程圖像加載界面。

看看吧here

0

創建一個類,並使用此

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(); 

     } 

     @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); 

     } 
} 

和主類

public void postHttpRequest(final String userId,final String pass,final TextView error){ 
     url = ""; 
     Log.d("URL", url); 
     RequestClient reqClient = new RequestClient(new CallBack() { 

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


       } catch (Exception e) { 
        Log.e("Exception Occured", "Exception is "+e.getMessage()); 
       } 
      } 
     }); 
     reqClient.execute(url); 
    } 

創建界面像這樣

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

希望這會幫助你 – Developer

相關問題