1

I have the following problem. After I got the android.os.NetworkOnMainThreadException I went looking for a solution, and as it seems, AsyncTask is the best way to handle this.

But after I read several pages I still don't know how to implement AsyncTask.

First I will tell you what i know so far together with my questions:

Here I would try to call the webservice.

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

    }
}

As far as I understand, the only thing I have to put here is

new MyClassName().execute(a, b, c);

right in my CheckStatus method. (This method is called, when a button is pressed)

So where does this line go?

private class MyClassName extends AsyncTask

I would now create a new class, give it a nice name and then put this line next

protected Long doInBackground(Params... params)

and then the code part of my CheckStatus .

Is this right so far?

The next thing is that I don't know, which parameters so you have to give the execute(a,b,c) call?

Can someone please give me some code example, using my code? I would really appreciate. I am sorry for asking so basic questions, but I don't understand how it works.

Thank you a lot for your help!

4

5 回答 5

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;               
            }
        }
    }

}
于 2013-07-30T10:47:54.180 回答
1

为什么不使用 Google Volley(在今年的 I/O 中介绍)。它有一个用于联网和远程图像加载的简单界面。

在这里查看。

于 2013-07-30T10:36:10.213 回答
1

首先,看看这里,然后看看这个例子

doInBackground()新创建的类中出现了所谓的“慢”代码。

于 2013-07-30T10:34:39.323 回答
0

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

异步任务由 3 个通用类型定义,称为 Params、Progress 和 Result,以及 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.
于 2013-07-30T10:33:08.357 回答
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);
}
于 2013-07-30T10:36:57.327 回答