CalledFromWrongThreadException - 只有创建视图层次结构的原始线程才能触及其视图

时间:2014-03-10 06:54:39

标签: android

我想通过webservice连接Mysql数据库。

    login = (Button) findViewById(R.id.btnGiris);
    login.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            Thread th = new Thread(new Runnable() {
                @Override
                public void run() {

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            new Authentication()
                                    .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

                        }
                    });
                }
            });
            th.start();

Webservice的身份验证类

    class Authentication extends AsyncTask<Void, Void, Void> {

    final String NAMESPACE = "http://aractakipyazilimlari.com";
    final String URL = "http://10.0.2.2:8080/IsbakApp/services/Login?wsdl";
    final String SOAP_ACTION = "http://aractakipyazilimlari.com/authentication";
    final String METHOD_NAME = "authentication";

    @Override
    protected Void doInBackground(Void... params) {

        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
        String user_Name = userName.getText().toString();
        String user_Password = userPassword.getText().toString();


        PropertyInfo unameProp = new PropertyInfo();
        unameProp.setName("plaka");
        unameProp.setValue(user_Name);
        unameProp.setType(String.class);
        request.addProperty(unameProp);

        PropertyInfo passwordProp = new PropertyInfo();
        passwordProp.setName("sifre");
        passwordProp.setValue(user_Password);
        passwordProp.setType(String.class);
        request.addProperty(passwordProp);

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.setOutputSoapObject(request);
        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

        try {
            androidHttpTransport.call(SOAP_ACTION, envelope);
            SoapObject response = (SoapObject) envelope.getResponse();
            result.setText(response.toString());

        } catch (Exception e) {

            Log.e("Login", e.toString());
        }

        return null;
    }

}

LogCat错误消息

  

android.view.ViewRootImpl $ CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能触及其视图

1 个答案:

答案 0 :(得分:0)

1 /您无法修改后台线程中的View,您需要在UI线程上执行此操作,这可以通过覆盖onPostExecute()来实现。此方法将doInBackground()返回的参数作为参数,在您的情况下为: response

此外,您还需要修改AsyncTask的签名:

class Authentication extends AsyncTask<Void, Void, String> {
}

由于第三种类型是指 doInBackground()返回的值的类型。

2 /正如Piyush所提到的,你不需要启动新的Thread,因为它正是AsyncTask的意思。