Error using AsyncTask more than once

1

I'm developing an application for android that connects to a webservice, to do 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 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).

The 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, the first time I ask a question here.

    
asked by anonymous 26.04.2018 / 03:40

1 answer

3

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

Notice that this is what the error 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);

    }
});
    
26.04.2018 / 12:58