Priority in progress

Asked

Viewed 731 times

9

It is possible to prioritize a progressdialog before a Thread? In my app, after clicking a button, I need to freeze a progressdialog for 2 seconds. After that, generate a query to my webservice, and as soon as return the data, they are presented in a alertdialog,that after opened, makes the progressdialog receive the dismiss() to close it. However, even instantiating a new Thread and setting the sleep() or wait(), the process just freezes the Thread for whole and does not present the progressdialog. On the screen, first the Alert is generated and the Progress is in the background until the Alert is closed.

Is there a possible way to generate Progress first with 2 seconds of Freeze and then the Alert dialog? Follows excerpt from 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();

                    }
  • 1

    Diego, I don’t understand where you’re wearing Thread in this code. Also use StrictMode.ThreadPolicy.Builder().permitAll() does not start a new Thread and is a bad practice because it masks some problems. This code is running on MainThread and consequently locking the interface, I recommend taking a look at this question to resolve this: http://answall.com/questions/33509/como-usar-a-biblioteca-ksoap2/33514#33514.

  • Wakim, I actually ended up posting the old code, sorry, if I instantiate a new thread, is there a way to put the progressidialog on hold to run on screen and freeze the 2 seconds? Or put the alertdialog itself on hold, for example. the code executes the progressidialog and displays on screen, then instantiates a new thread, puts this thread on hold for 2 seconds, and then executes the alertdialog showing the information returned by the URL. There is a way to adapt the code to run this way?

  • 2

    Yes it is possible, but I recommend another approach. Display a DialogFragment (using cancelable as false) and start a AsyncTask in the onViewCreated, updating it at the end of processing in the method onPostExecute.

  • I will test here now! Thank you very much.

  • You can try to perform the data search process in another thread, for example only when the thread has finished its execution would you call the demiss of the alertDialog... although maybe it is not the best solution..

2 answers

1

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

You could use a AsyncTask, then in the method onPreExecute, you start your ProgressDialog, in the method doInBackground you make your Http call and method onPostExecute, you finalize your ProgressDialog and displays his AlertDialog.

Read more about Asynctask

1

It is right to do this using an Asynctask

-Your Victoria 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));
    }
}

-And the processing is on account of 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

Browser other questions tagged

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