-1

我在我的第一个活动中使用 AsyncTask 类,它工作正常并调用第二个,我在 onCreate 中调用另一个 AsyncTask 调用对象并在 doInBackground 中调用 web 服务,然后它给出异常 android.os.networkmainthread。

我不知道,因为我是 android 开发的新手,所以请给我看一些示例,或者我给你看我的代码

这是我的代码

public class panel extends Activity {


@Override
 public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.panel);
   User_Balance_Load Balance_load=new User_Balance_Load();
   Balance_load.execute();
   Toast.makeText(getBaseContext(),Cls_Constant.username, Toast.LENGTH_LONG).show();



}
class User_Balance_Load extends AsyncTask<Void, Void, Void>
{
    private final ProgressDialog dialog = new ProgressDialog(panel.this);
    protected void onPreExecute() { 

        this.dialog.setMessage("Loding Diet type..."); 
        this.dialog.show(); 
                                    } 

    protected Void doInBackground(final Void... unused) {
        // TODO Auto-generated method stub
        panel.this.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                Update_balance();
            }
        });
        return null;
    }
    protected void onPostExecute(Void result)  
    { 

            if (this.dialog.isShowing()) 
            { 
            this.dialog.dismiss(); 
            }


     } 

}
void Update_balance()
{

    Vector result;
    result=Cls_webservice.User_Balance(Cls_Constant.Guid);
    if(result.size()>0)
    {
        String UserBalance=result.elementAt(2).toString();
        TextView Tv_User_balacne=(TextView)findViewById(R.id.tv_point_balance);
        Tv_User_balacne.setText(UserBalance);
    }
}

这是我的网络服务类

public class Cls_webservice {


 public static Vector User_Balance(String id)
    { 
        Vector _vector = new Vector();
        final String userid = id;

        final String METHOD_NAME = "WCFDatatableRes";
        final String SOAP_ACTION = "http://tempuri.org/WCFDatatableRes";
        final String NAMESPACE = "http://tempuri.org/";
        final String URL = "http://xxxxxxxx.com/GameRoom/ANDROIDLOTT/WebService.asmx";
        String return_val="";
        SoapObject newob;
        try
        {
            Object response;
            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
            envelope.encodingStyle = SoapEnvelope.ENC;
            SoapObject Request = new SoapObject(NAMESPACE , METHOD_NAME);
            Request.addProperty("Params", userid+",3"); 
            Request.addProperty("Do", "Balance"); 
            envelope.dotNet = true;
            envelope.setOutputSoapObject(Request);
            AndroidHttpTransport httptransport ;
            httptransport = new AndroidHttpTransport(URL);

            httptransport.debug=true;
            try
            {

                httptransport.call(SOAP_ACTION,envelope);
                response = envelope.getResponse();
                newob = (SoapObject)envelope.bodyIn;
                return_val = newob.toString();
                SoapObject diettype_listResult = (SoapObject) newob.getProperty("WCFDatatableRes ") ;
                SoapObject diffgram = (SoapObject) diettype_listResult.getProperty("diffgram") ;

            }
            catch (Exception e) {
                System.out.println("error:" + e);
            }                 

        }
        catch (Exception e) {
        }
        return _vector;
    }

}

异常出现在这一行 - >“httptransport.call(SOAP_ACTION,envelope); 所以请帮助我,同样的代码在我的第一个活动中工作我不知道为什么在第二次出现错误谢谢

4

2 回答 2

1

NetworkOnMainThread 发生异常是因为您正在 UI 线程上运行与网络相关的操作。这仅针对面向 Honeycomb SDK 或更高版本的应用程序抛出。允许以早期 SDK 版本为目标的应用程序在其主事件循环线程上进行网络连接,但非常不鼓励这样做。请参阅文档设计响应性。

您正在使用 runonUithread 运行 Update_balance()。

您正在尝试通过调用 Update_balance() 来更新 doInBackground() 中的 ui,该方法将 textview 中的文本设置如下。您不应该在 doInBackground() 中更新 ui。

TextView Tv_User_balacne=(TextView)findViewById(R.id.tv_point_balance);
    Tv_User_balacne.setText(UserBalance);TextView Tv_User_balacne=(TextView)findViewById(R.id.tv_point_balance);
    Tv_User_balacne.setText(UserBalance);

所有与网络相关的操作都应该在 doInBackground() 中完成。在 doInBackground() 中调用 Web 服务。

doInBackground()您可以从检索中返回值onPostExecute()并相应地更新 ui。

class TheTask extends AsyncTask<Void,Void,Void>
{
 protected void onPreExecute()
 {           super.onPreExecute();
        //display progressdialog.
 }  

protected void doInBackground(Void ...params)//return result here
{  
    //http request. do not update ui here
    //call webservice
    //return result here
    return null;
} 

protected void onPostExecute(Void result)//result of doInBackground is passed a parameter
{     
        super.onPostExecute(result);
        //dismiss progressdialog.
        //update ui using the result returned form doInbackground()

} 

}

4 个步骤 当一个异步任务被执行时,该任务会经历 4 个步骤:

  1. onPreExecute(),在任务执行之前在 UI 线程上调用。此步骤通常用于设置任务,例如通过在用户界面中显示进度条。

  2. doInBackground(Params...),在 onPreExecute() 完成执行后立即在后台线程上调用。此步骤用于执行可能需要很长时间的后台计算。异步任务的参数传递到这一步。计算的结果必须由这一步返回,并将传递回最后一步。此步骤还可以使用 publishProgress(Progress...) 来发布一个或多个进度单位。这些值在 UI 线程上的 onProgressUpdate(Progress...) 步骤中发布。

  3. onProgressUpdate(Progress...),在调用 publishProgress(Progress...) 后在 UI 线程上调用。执行的时间是不确定的。此方法用于在后台计算仍在执行时在用户界面中显示任何形式的进度。例如,它可用于动画进度条或在文本字段中显示日志。

  4. onPostExecute(Result),在后台计算完成后在 UI 线程上调用。后台计算的结果作为参数传递给该步骤。

欲了解更多详情,请查看以下链接

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

于 2013-04-08T07:53:50.113 回答
0

您正在使用 asynctask,然后在您的 asynctask 中,您正在 UI 线程下运行代码。这是废话,因为结果与在 OnCreate() 方法上执行代码相同。

protected Void doInBackground(final Void... unused) 
{
    Vector result = Update_balance();
    panel.this.runOnUiThread(new Runnable() 
    {
        @Override
        public void run()
        {
            if(result.size()>0)
            {
                String UserBalance=result.elementAt(2).toString();
                TextView Tv_User_balacne=(TextView)findViewById(R.id.tv_point_balance);
                Tv_User_balacne.setText(UserBalance);
            }                
        }
    });
    return null;
}

Vector Update_balance()
{
    Vector result;
    result=Cls_webservice.User_Balance(Cls_Constant.Guid);
    return result;
}
于 2013-04-08T08:39:33.940 回答