2

I saw that .get() is the problem, but I try without him and nothing. If possible help me. The ProgressDialog execute after doInBackground() and after run onPostExecute "dismiss" and then ProgressDialog not show.

    public List<Usuario> getListaUsuario(Activity activity) {
        String[] aux = new String[3];
        aux[0] = URL_WS_USUARIO;
        String[] resposta = null;
        aux[2] = "GET";

        try {
            resposta = new WebServiceCliente(activity).execute(aux).get();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (resposta[0].equals("200")) {
            Gson gson = new Gson();
            ArrayList<Usuario> listaCliente = new ArrayList<Usuario>();
            JsonParser parser = new JsonParser();
            JsonArray array = parser.parse(resposta[1]).getAsJsonArray();
            for (int i = 0; i < array.size(); i++) {
                listaCliente.add(gson.fromJson(array.get(i), Usuario.class));
            }
            return listaCliente;

        } else {
            return null;

        }
    }


MY ASYNCTASK:

public class WebServiceCliente extends AsyncTask<String, Void, String[]> {

    private Activity activity;
    private ProgressDialog pDialog;

    public WebServiceCliente(Activity ac) {
        activity = ac;
    }

    public final String[] get(String url) {
        String[] result = new String[2];
        HttpGet httpget = new HttpGet(url);

        HttpResponse response;

        try {
            response = HttpClientSingleton.getHttpClientInstace().execute(
                    httpget);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                result[0] = String.valueOf(response.getStatusLine()
                        .getStatusCode());
                InputStream instream = entity.getContent();
                result[1] = toString(instream);
                instream.close();
                Log.i("get", "Result from post JsonPost : " + result[0] + " : "
                        + result[1]);
            }
        } catch (Exception e) {
            Log.e("NGVL", "Falha ao acessar Web service", e);
            result[0] = "0";
            result[1] = "Falha de rede!";
        }
        return result;
    }

    public final String[] post(String url, String json) {
        String[] result = new String[2];
        try {

            HttpPost httpPost = new HttpPost(new URI(url));
            httpPost.setHeader("Content-type", "application/json");
            StringEntity sEntity = new StringEntity(json, "UTF-8");
            httpPost.setEntity(sEntity);

            HttpResponse response;
            response = HttpClientSingleton.getHttpClientInstace().execute(
                    httpPost);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                result[0] = String.valueOf(response.getStatusLine()
                        .getStatusCode());
                InputStream instream = entity.getContent();
                result[1] = toString(instream);
                instream.close();
                Log.d("post", "Result from post JsonPost : " + result[0]
                        + " : " + result[1]);
            }

        } catch (Exception e) {
            Log.e("NGVL", "Falha ao acessar Web service", e);
            result[0] = "0";
            result[1] = "Falha de rede!";
        }
        return result;
    }

    private String toString(InputStream is) throws IOException {

        byte[] bytes = new byte[1024];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int lidos;
        while ((lidos = is.read(bytes)) > 0) {
            baos.write(bytes, 0, lidos);
        }
        return new String(baos.toByteArray());
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        pDialog = new ProgressDialog(activity);
        pDialog.setCanceledOnTouchOutside(false);
        pDialog.setCancelable(false);
        pDialog.setIndeterminate(true);
        pDialog.setTitle("Conectando Servidor.");
        pDialog.setMessage("Aguarde...");
        pDialog.show();

    }

    @Override
    protected String[] doInBackground(String... params) {

        if (params[2] == "POST") {

            return post(params[0], params[1]);

        } else if (params[2] == "GET") {

            return get(params[0]);
        } else {
            return null;
        }

    }

    @Override
    protected void onPostExecute(String[] params) {

        super.onPostExecute(params);

        try {
            // stop Dialog
            if (pDialog.isShowing()) {
                pDialog.dismiss();
            }

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

    }

}
Neto
  • 92
  • 2
  • 12

1 Answers1

2

The problem is

new WebServiceCliente(activity).execute(aux).get();

get() is a blocking call, and with the UI Thread blocked waiting for get() to return there is no one that can take care of drawing the ProgressDialog. Remove get(), and use a Delegate to return the results on your AsyncTask to the UI Thread, Here there is an example

Edit:

your interface should be like:

public interface CallbackReciever { public void receiveData(String[] result); }

the constructor of your AsynTask changes like

CallbackReciever mListener;
public WebServiceCliente(Activity ac, CallbackReciever listener) {
    activity = ac;
    mListener = listener;
}

in onPostExecute:

@Override
protected void onPostExecute(String[] params) {

try {
    if (mListener != null) {
       mListener.receiveData(params);
    }

    // stop Dialog
    if (pDialog.isShowing()) {
        pDialog.dismiss();
    }

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

In receiveData, in your Activity, you have to process String[] result

Community
  • 1
  • 1
Blackbelt
  • 156,034
  • 29
  • 297
  • 305
  • Thank you Blackbelt, I will try this solution. – Neto May 31 '15 at 13:49
  • BackBelt, I tried like your example, .get() was removed and delegated results on my AsyncTask by interface. But don't worked, how to do for "String[ ] resposta" receive the result? and when I remove my "dialog.dismiss" the progressDialog is showed – Neto May 31 '15 at 18:34
  • ok BlackBelt I did how you said, but and "resposta = new WebServiceCliente(activity).execute(aux).get();" what I will put in place this line? – Neto Jun 01 '15 at 11:17
  • because the variable resposta is populated after onPostExecute, and in this case I use if (resposta[0].equals("200")) before onPostExecute be called... and then resposta right now is null – Neto Jun 01 '15 at 14:01
  • `resposta` is populated by `doInBackground`. You have to move all the `resposta[0].equals("200"))` logic inside `receiveData` – Blackbelt Jun 01 '15 at 14:11
  • the last one friend, do you agree with me that doInBackground is called after onPreExecute? But when I do rest.getListaUsuario(LoginActivity.this); this line call asyncTask, bellow this line i have salvarUsuariosByWebServices(rest.getListaUser()); my doInBackground is called only after salvarUsuariosByWebServices(rest.getListaUser()) why? Do you know? – Neto Jun 01 '15 at 17:29
  • The order of execution is onPreExecute -> doInBackground -> onPostExecute – Blackbelt Jun 01 '15 at 17:43
  • ok... my doInBackground is called, but is executed onPreExecute() - OK, after this, dont call my doInBackground, call salvarUsuariosByWebServices(rest.getListaUser()) after this my doInBackground is called. – Neto Jun 01 '15 at 18:11
  • nice. You should delete your answer below – Blackbelt Jun 02 '15 at 14:09