NetworkOnMainThreadException崩溃Android应用程序

时间:2015-03-02 07:36:10

标签: networkonmainthread

我构建了一个Web服务并使用SoapUI对其进行了测试,一切正常。现在当我尝试提交表单来注册用户时,我收到NetworkOnMainThreadException错误。它看起来主要线程需要做很多工作。

你能帮我解决AsyncTask和doInBackground()方法吗?我应该在哪里以及如何做到这一点?在我的用户注册布局类(RegUser.java)或insert方法的位置(UserDAO.java)?

RegUser.java

public class RegUser extends Activity {

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

    final EditText username = (EditText) findViewById(R.id.username);
    final EditText email = (EditText) findViewById(R.id.email);
    final EditText password = (EditText) findViewById(R.id.password);
    final EditText salt = (EditText) findViewById(R.id.salt);
    final EditText nome = (EditText) findViewById(R.id.nome);
    final EditText sobrenome = (EditText) findViewById(R.id.sobrenome);
    final EditText telefone = (EditText) findViewById(R.id.telefone);
    final EditText cel_wts = (EditText) findViewById(R.id.cel_wts);
    final EditText rua = (EditText) findViewById(R.id.rua);
    final EditText numero = (EditText) findViewById(R.id.numero);
    final EditText bairro = (EditText) findViewById(R.id.bairro);
    final EditText cidade = (EditText) findViewById(R.id.cidade);
    final EditText estado = (EditText) findViewById(R.id.estado);
    final EditText pais = (EditText) findViewById(R.id.pais);
    final EditText cpf_cnpj = (EditText) findViewById(R.id.cpf_cnpj);
    final EditText empresa= (EditText) findViewById(R.id.empresa);
    final EditText cargo = (EditText) findViewById(R.id.cargo);

    final Button cadProfile = (Button) findViewById(R.id.cadProfile);

    cadProfile.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            UserDAO dao = new UserDAO();
            boolean resultado = dao.insertUser(new User(0, username.getText().toString(),
                    email.getText().toString(),
                    password.getText().toString(),
                    salt.getText().toString(),
                    nome.getText().toString(),
                    sobrenome.getText().toString(),
                    telefone.getText().toString(),
                    cel_wts.getText().toString(),
                    rua.getText().toString(),
                    numero.getText().toString(),
                    bairro.getText().toString(),
                    cidade.getText().toString(),
                    estado.getText().toString(),
                    pais.getText().toString(),
                    cpf_cnpj.getText().toString(),
                    empresa.getText().toString(),
                    cargo.getText().toString()));

            if(resultado){
                finish();
            }else{
                Toast.makeText(RegUser.this, "Erro ao cadastrar :(", Toast.LENGTH_LONG).show();
            }

        }
    });

}
}

UserDAO.java

public class UserDAO {

private static final String URL = "...meuIP:8080/Meuprojeto/services/EventoDAO?wsdl";
private static final String NAMESPACE = "...meuprojetoWS.habitodigital.com";

private static final String INSERIR = "insertUser";
private static final String EXCLUIR = "deletetUser";
private static final String ATUALIZAR = "updateUser";
private static final String BUSCAR_TODOS = "searchAllUsers";
private static final String BUSCAR_POR_ID = "searchUserById";


public boolean insertUser(User user){

SoapObject insertUser = new SoapObject(NAMESPACE, INSERIR);
SoapObject usr = new SoapObject(NAMESPACE, "user");

usr.addProperty("id", user.getId());
usr.addProperty("username", user.getUsername());
usr.addProperty("email", user.getEmail());
usr.addProperty("password", user.getPassword());
usr.addProperty("salt", user.getSalt());

usr.addProperty("nome", user.getNome());
usr.addProperty("sobrenome", user.getSobrenome());
usr.addProperty("telefone", user.getTelefone());
usr.addProperty("cel_wts", user.getCel_wts());
usr.addProperty("rua", user.getRua());
usr.addProperty("numero", user.getNumero());
usr.addProperty("bairro", user.getBairro());
usr.addProperty("cidade", user.getCidade());
usr.addProperty("estado", user.getEstado());
usr.addProperty("pais", user.getPais());
usr.addProperty("cpf_cnpj", user.getCpf_cnpj());
  usr.addProperty("empresa", user.getEmpresa());
usr.addProperty("cargo", user.getCargo());

insertUser.addSoapObject(usr);

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(insertUser);

envelope.implicitTypes = true;

HttpTransportSE http = new HttpTransportSE(URL);
 try {

http.call("urn:" + INSERIR, envelope);
SoapPrimitive resposta = (SoapPrimitive) envelope.getResponse();

return Boolean.parseBoolean(resposta.toString());

} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}

1 个答案:

答案 0 :(得分:0)

我应该在userDOA.java中执行此操作。 ASynctask看起来像这样。

        AsyncTask<String, Void, Boolean) task =new AsyncTask<String, Void, Boolean>() {

        @Override
        protected Boolean doInBackground(String... params) {
            HttpTransportSE http = new HttpTransportSE(URL);
            try {

                http.call("urn:" + INSERIR, envelope);
                SoapPrimitive resposta = (SoapPrimitive) envelope.getResponse();

                return Boolean.parseBoolean(resposta.toString());
            } catch (Exception e) {
                //handle exception
            }
        }

        @Override
        protected void onPostExecute(Boolean result) {
            //Do something with result
        }
    }

您需要将其称为

task.execute(params);

希望这有帮助。