Jump to content

AssyncTask, usar apenas uma vez


Carlos Rocha

Recommended Posts

Fala povo!

Feliz Ano Novo a todos e a todas!

Então, estou fazendo a seguinte classe que estende AssyncTask

private class HttpService extends AsyncTask<String, Integer, String> {

O que ocorre é que terei que chamar esse classe umas 4 vezes no mesmo arquivo e ele fica muito grande!

No entanto, não consegui criar essa solução

O jeito foi usar o onPosExecute() mesmo e repetir a classe HttpService 3 vezes.

Uma para cada operação.

Algum recurso?

É que em algumas chamadas precisarei passar um token no cabeçalho (header) da requisição e em outros não.

Vejam com estou tentando!

package br.net.concertacell;

import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import br.net.concertacell.classes.Orcamentos;

public class Cadastrar extends AppCompatActivity {
    private Bundle tokenWS;
    private String token;
    private Spinner spCliente;
    private Spinner spEquipamento;
    private EditText etEstado;
    private EditText etDefeitoRelatado;
    private Button btnCadastrar;
    private TextView tvResposta;

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

        tokenWS = getIntent().getExtras();
        token = tokenWS.getString("tokenWS");

        tvResposta = findViewById(R.id.tvResposta);
        spCliente = findViewById(R.id.spClientes);
        spEquipamento = findViewById(R.id.spEquipamento);
        etEstado = findViewById(R.id.etEstado);
        etDefeitoRelatado = findViewById(R.id.etDefeitoRelatado);

        obtemListaClientes ();
        obtemListaEquipamentos ();

    }

    private void obtemListaClientes() {

        String urlClientes = "https://acweb.net.br/api/clientes/listar";
        HttpService htClientes = new HttpService();
        htClientes.execute(urlClientes, this.token, "", "spCliente");
    }

    private void obtemListaEquipamentos() {

        String urlEquipamentos = "https://acweb.net.br/api/equipamentos/listar";
        HttpService htEquipamentos = new HttpService();
        htEquipamentos.execute(urlEquipamentos, this.token, "", "spEquipamento");

    }

    public void cadastrar(View view) throws IOException {

        String url = "https://acweb.net.br/api/orcamentos/cadastrar";

        Orcamentos orcamento = new Orcamentos(
                2,
                2,
                "Aparelho não liga",
                "PÉSSIMO"
        );

        HttpService htOrcamentos = new HttpService();
        htOrcamentos.execute(url, this.token, orcamento.toString());

    }


    private class HttpService extends AsyncTask<String, Integer, String> {

        ProgressDialog progressDialog;

        @Override
        protected void onPreExecute() {

            progressDialog = new ProgressDialog(Cadastrar.this);
            progressDialog.setTitle("Aguarde");
            progressDialog.setMessage("Processando...");
            progressDialog.setCancelable(false);
            progressDialog.show();

        }

        @Override
        protected String doInBackground(String... args) {

            String resposta = "";

            try {
                URL url = new URL(args[0]);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
                conn.setRequestProperty("Accept", "application/json");
                conn.setRequestProperty("token", args[1]);
                conn.setDoOutput(true);
                conn.setDoInput(true);

                DataOutputStream os = new DataOutputStream(conn.getOutputStream());

                if (!args[2].equals(""))
                    os.writeBytes(args[2]);

                os.flush();
                os.close();

                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String inputLine;
                String linha = "";

                while ((inputLine = in.readLine()) != null) {

                    Log.i("inputLine: ", inputLine.toString());
                    resposta += inputLine;
                }
                in.close();

                conn.disconnect();


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

            return [resposta, args[3]];

        }

        @Override
        protected void onPostExecute(String str) {

            progressDialog.cancel();

            JSONObject retorno = null;

            try {

                retorno = new JSONObject(str);
                Log.i ("Resultado", retorno.toString());
                tvResposta.setText(retorno.getString("mensagem"));

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        protected void onProgressUpdate(Integer... text) {
            super.onProgressUpdate(text);

        }


    }

}

Já estou perdido

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.