Priority in progressdialog

10

Is it possible to prioritize progressdialog vs. Thread ? In my app, after clicking a button, I need to freeze progressdialog for 2 seconds. After that, I generate a query to my webservice , and as soon as I return the data, they are presented in alertdialog , which after opening, causes progressdialog to receive dismiss() to close it. However, even instantiating a new Thread and setting sleep() or wait() , the process only freezes Thread for integer and does not display progressdialog . On the screen, first the alert is generated and the progress stays in the background until the alert is closed.

Is there a possible way to first generate Progress with 2 seconds of freeze and then the alert dialog? Here is the snippet of the code.

    final EditText Nome = (EditText) findViewById(R.id.cmdDigDe);
    Button btnConDeE = (Button) findViewById(R.id.btnConDe);
    btnConDeE.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            ProgressDialog progressDialog = new ProgressDialog(DemE.this);
            progressDialog.setTitle("Listando medicamentos");
            progressDialog.setMessage("Buscando...");
            progressDialog.show();

                String nomeProduto = Nome.getText().toString();
                String laboratorio = null;
                String aliquota = "17";

                if (android.os.Build.VERSION.SDK_INT > 9) {
                    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                    StrictMode.setThreadPolicy(policy);
                }

                if (nomeProduto == "") {
                    Toast.makeText(DemE.this, "Por favor digite o nome do medicamento", Toast.LENGTH_LONG).show();
                } else

                    try {
                        URL url = new URL("http");
                        URLConnection con = url.openConnection();
                        con.setDoOutput(true);
                        OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());

                        writer.write("nome=" + nomeProduto + "&aliquota=" + aliquota + (laboratorio != null ? "&laboratorio=" + laboratorio : ""));
                        writer.flush();

                        BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                        String result = "";
                        String line;


                        while ((line = reader.readLine()) != null) {

                            result += line;

                            TextView tv = (TextView) findViewById(R.id.tv);
                            tv.setText(Html.fromHtml(result));

                            final String text = tv.getText().toString();


                            AlertDialog alertDialog = new AlertDialog.Builder(context).create();
                            alertDialog.setTitle("Medicamentos:");
                            alertDialog.setMessage(text);
                            alertDialog.setButton("Voltar", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    dialog.cancel();
                                }
                            });

                            progressDialog.dismiss();
                            alertDialog.show();


                        }

                        writer.close();
                        reader.close();

                    }
    
asked by anonymous 26.02.2015 / 18:41

2 answers

1

Diego, I see some strange things in your code, for example, you're calling the AlertDialog alertDialog = new AlertDialog.Builder(context).create(); method inside the loop ( while ). Second, you are running a process that may take a while inside the main Thread.

You could use AsyncTask , so in onPreExecute method, you start ProgressDialog , in method doInBackground you make your Http call and onPostExecute method, you finalize your ProgressDialog and it displays its AlertDialog .

Read more about AsyncTask

    
11.01.2017 / 12:00
1

The right thing to do is to use an AsyncTask

-Your activity would look like this:

public class DemE extends Activity implements View.OnClickListener
{
    //Suponho que seja aqui aonde você roda o metodo
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        findViewById(R.id.btnConDe).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        String nomeProduto =  findViewById(R.id.cmdDigDe).getText().toString();
        String laboratorio = null;
        String aliquota = "17";


        if (nomeProduto == "") 
            Toast.makeText(DemE.this, "Por favor digite o nome do medicamento", Toast.LENGTH_LONG).show();
        else
            new BuscaMedicamentosAsync(this).execute(
                new StringBuilder("nome=")
                        .append(nomeProduto)
                        .append("&aliquota=")
                        .append(aliquota)
                        .append("&laboratorio=")
                        .append(laboratorio == null? "" : laboratorio));
    }
}

-E processing is by async:

public final class BuscaMedicamentosAsync extends AsyncTask<CharSequence, Integer, CharSequence>
{
    private final AlertDialog alertDialog;
    private final ProgressDialog progressDialog;

    public BuscaMedicamentosAsync(Context contexto)
    {
        this.alertDialog = new AlertDialog.Builder(contexto).create();
        alertDialog.setTitle("Medicamentos:");
        alertDialog.setButton(0, "Voltar", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });

        progressDialog = new ProgressDialog(contexto);
        progressDialog.setTitle("Listando medicamentos");
        progressDialog.setMessage("Buscando...");
        progressDialog.show();
        progressDialog.setCancelable(false); //Impedir que o usuario feche o dialogo
    }

    @Override
    protected CharSequence doInBackground(CharSequence... parametros)
    {
        StringBuilder result = new StringBuilder();
        try {
            URL url = new URL("http");
            URLConnection con = url.openConnection();
            con.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());

            writer.write(parametros[0].toString());
            writer.flush();

            BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String line;


            while ((line = reader.readLine()) != null) {

                result.append(line);
            }

            writer.close();
            reader.close();

        } catch (Exception e) {
            //Trata a exceção
        }

        return Html.fromHtml(result.toString()).toString();
    }

    @Override
    protected void onPostExecute(CharSequence text) {
        super.onPostExecute(text);

        progressDialog.dismiss();

        alertDialog.setMessage(text);
        alertDialog.show();
    }
}

Recommended reading

18.10.2017 / 17:58