Error using Asynctask more than once

Asked

Viewed 49 times

2

I am developing an application for android that connects to a webservice, to make the connection part I used an Asynctask to avoid crashes, but when I run the application I can register the user only once, after that if I try to register again it returns me the following error in Logcat:

java.lang.IllegalStateException: Cannot execute task: the task has already been executed (a task can be executed only once).

Error points to line 72: backGround.execute(Nome_funcionario,Email_funcionario,Senha_funcionarios);

    final BackGround backGround = new BackGround(this);


    cadastrar.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view) {

            String Nome_funcionario = nome.getText().toString();
            String Email_funcionario = email.getText().toString();
            String Senha_funcionarios = senha.getText().toString();

            Log.i("AsyncTask", "AsyncTask senado chamado Thread: " + Thread.currentThread().getName());
            backGround.execute(Nome_funcionario,Email_funcionario,Senha_funcionarios);

        }
    });

    class BackGround extends AsyncTask<String,Void,String>{

    Context context;
    BackGround(Context ctx) {

        context = ctx;
    }

    @Override
    protected String doInBackground(String... strings) {
        String UrlInserir = "http://ipdopc/include2/insertFuncionario.php";

        try {

            String Nome_funcionario = strings[0];
            String Email_funcionario = strings[1];
            String Senha_funcionarios = strings[2];

            URL url = new URL(UrlInserir);

            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();

            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("Nome_funcionario", "UTF-8") + "=" + URLEncoder.encode(Nome_funcionario, "UTF-8") + "&"
                    + URLEncoder.encode("Email_funcionario", "UTF-8") + "=" + URLEncoder.encode(Email_funcionario, "UTF-8") + "&"
                    + URLEncoder.encode("Senha_funcionarios", "UTF-8") + "=" + URLEncoder.encode(Senha_funcionarios, "UTF-8");

            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();

            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
            String resultado = "";
            String linha = "";

            while ((linha = bufferedReader.readLine()) != null) {
                resultado += linha;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();

            JSONObject jsonObject = new JSONObject(resultado);
            if (jsonObject.names().get(0).equals("existente")){
                return "Email ja existente.";
            }else if (jsonObject.names().get(0).equals("cadastrado")){

                Intent intent = new Intent(CadastrarActivity.this,MainActivity.class);

                startActivity(intent);

            }else if (jsonObject.names().get(0).equals("vazio")){
                return "Preencha todos os campos.";
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
      return null;
    }
    @Override
    protected void onPostExecute(String resultado) {
        textView.setText(resultado);
    }
}

Any mistake I’m sorry, first time I ask a question here.

1 answer

3


The method execute() of an Asynctask can only be used once. You must always create a new instance so that you can use it.

Note that this is what the bug reports:

java.lang.IllegalStateException: Cannot execute task: the task has already been executed (a task can be executed only once).

Change the code like this:

//Não é mais necessária, uma nova instância é criada dentro do onClick()
//final BackGround backGround = new BackGround(this);

cadastrar.setOnClickListener(new View.OnClickListener(){
    @Override
    public void onClick(View view) {

        //Cria uma nova instância de BackGround
        BackGround backGround = new BackGround(NomeDaSuaActivity.this);

        String Nome_funcionario = nome.getText().toString();
        String Email_funcionario = email.getText().toString();
        String Senha_funcionarios = senha.getText().toString();

        Log.i("AsyncTask", "AsyncTask senado chamado Thread: " + Thread.currentThread().getName());
        backGround.execute(Nome_funcionario,Email_funcionario,Senha_funcionarios);

    }
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.