Android: Problem with ProgressBar

1

I have a problem when I show my ProgressBar what happens is that the ProgressBar appears already until the last one and its appearance of immediate that is not reached to appreciate. What I want to do is show up when I'm in AsyncTask and it actually lasts what the request brings. I hope and you can help me

activity_main.xml

<ProgressBar
            android:id="@+id/progressBar"
            style="?android:attr/progressBarStyleLarge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:visibility="gone"
            android:indeterminateDrawable="@drawable/progress" >
        </ProgressBar>

progress.xml

<?xml version="1.0" encoding="utf-8"?>

<shape
    android:innerRadiusRatio="3"
    android:shape="ring"
    android:thicknessRatio="8"
    android:useLevel="false" >
    <size
        android:height="48dip"
        android:width="48dip" />

    <gradient
        android:centerColor="#58FAD0"
        android:centerY="0.50"
        android:endColor="#2E64FE"
        android:startColor="#FF00BF"
        android:type="sweep"
        android:useLevel="false" />
</shape>

MainActivity.java

   public class MainActivity extends AppCompatActivity {

    private ImageButton btnScanner;
    private Button btnCode;
    private EditText txtCode;
    private TextView movement;
    ProgressBar progressBar;

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

        progressBar = (ProgressBar) findViewById(R.id.progressBar);

        btnScanner = (ImageButton) findViewById(R.id.btn_scanner);
        btnCode = (Button) findViewById(R.id.btn_code);
        txtCode = (EditText) findViewById(R.id.text_code);


        final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

        btnScanner.setOnClickListener(new View.OnClickListener() {//del objeto View se llama al metodo OnClick LIstener
            @Override
            public void onClick(View view) {//./se implementa el metodo de OnClickListener
                Intent intentScanner = new Intent(MainActivity.this, ScannerActivity.class);//creo un intenet para abrir el escaner
                startActivity(intentScanner);//inicio la actividad
            }//./OnClick
        });//./OnclickLIstener

        btnCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (txtCode.getText().toString().trim().equals("")) {//obtengo el texto lo convierto a string y comparo con vacion
                    Toast.makeText(MainActivity.this, "El campo esta vacio",//mando un toast (mensaje porque el campo esta vacio)
                            Toast.LENGTH_SHORT).show();//por cortotiempo y lo muestro
                } else {
                    if (txtCode.getText().toString().trim().matches("[0-9]*")){//compruebo que los datos que se ingresaron son numeros
                        int inputData = Integer.parseInt(txtCode.getText().toString());//convierto lo que en el editText a int

                        progressBar.setVisibility(View.VISIBLE);
                        int parameters[] = {inputData};
                        SearchDataa searchDataa = new SearchDataa();
                        CheckIn checkIn = null;//hago una instancia de DataCheckIn y la guado en una variable
                        try {
                            checkIn = searchDataa.execute(parameters).get();//le paso el folio como parametro a SearchData
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (ExecutionException e) {
                            e.printStackTrace();
                        }
                            if (checkIn != null && checkIn.getFolio() == inputData){
                                Intent intentIndex = new Intent(MainActivity.this, IndexActivity.class);//Creo un intent
                                startActivity(intentIndex);//inicio la actividad
                                finish();//se destruye la actividad
                            } else {
                                alertDialogBuilder.setTitle("ERROR..").setMessage("El codigo no se encontro").setCancelable(false).setPositiveButton("ACEPTAR", null).show(); //mensaje si no existe el checkin
                                txtCode.setText("");
                            } //./else
                    } else {
                        alertDialogBuilder.setTitle("ERROR..").setMessage("El codigo no se encontro").setCancelable(false).setPositiveButton("ACEPTAR", null).show(); //mensaje si no existe el checkin
                        txtCode.setText("");
                    } //./else
                } //./else*/
            } //./onClick
        }); //./Listener
    }//./constructor

    class SearchDataa extends AsyncTask<Object, Integer, CheckIn> {
        @Override
        protected CheckIn doInBackground(Object... params) {//ejecuta nuestras tareas principales
            CheckIn checkIn = CheckIn.getInstance();

            CloseableHttpClient httpClient;
            CloseableHttpResponse httpResponse;

            try {
                HttpGetHC4 httpGetHC4 = new HttpGetHC4(DynamicUrl.BASE_URL+DynamicUrl.SERVER_HOST+":"+DynamicUrl.SERVER_PORT+DynamicUrl.SERVER_ROUTE);//a que servidor se va a apuntar
                httpClient = HttpClients.createDefault();//aqui se realiza la configuracion por default
                httpResponse = httpClient.execute(httpGetHC4);//aqui se encuentran los datos de la peticion


                JSONObject jsonRootObject = new JSONObject(EntityUtilsHC4.toString(httpResponse.getEntity()));//creo un JSON y le asigono mi respuesta que optuve
                JSONObject jsonData = jsonRootObject.getJSONObject("data");//en este json estan unicamente los datos
                System.out.println("este es el JSONObject "+jsonRootObject);

                if (jsonRootObject.getString("code").equals("OK")){//checo que el jsonRootObject tenga la clave "OK"
                    int folio = jsonData.getInt("folio");//del JSON jalo el folio
                    String customer = jsonData.getString("customer");//del JSON jalo el cliente
                    String delivered = jsonData.getString("delivered");//del JSON jalo la fecha_entrega
                    JSONArray images = jsonData.getJSONArray("images");//paso a un JSONArray el arreglo de las imagenes


                    if (images != null) {//checo que el JSONArray traiga imagenes
                        ArrayList<Bitmap> arrayBitmaps = new ArrayList<Bitmap>();//creo un arreglo de Bitmaps
                        for (int i = 0; i < images.length(); i++) {//itero el JSONArray

                            URL url = new URL(images.getString(i));//paso la url donde se encuentra la imagen
                            HttpURLConnection connection = (HttpURLConnection) url.openConnection();//abre la conexion o crea la conexion
                            connection.setDoInput(true);//usar la conexión de URL para la entrada de datos
                            connection.connect();//realiza la conexion
                            InputStream input = connection.getInputStream();//lee el flujo de entrada de bytes que trae la conexion
                            Bitmap myBitmap = BitmapFactory.decodeStream(input);//se decodifican los bytes a Bitmap
                            arrayBitmaps.add(myBitmap);//se pasa al arreglo de Bitmaps
                        }//./for
                        checkIn.setImages(arrayBitmaps);//seteo el arreglo de Bitmaps

                    }//./if
                    checkIn.setFolio(folio);//setteo el folio
                    checkIn.setCustomer(customer);//setteo el customer
                    checkIn.setDelivered(delivered);//setteo el

                } else {
                    checkIn = null;
                }//./else
            } catch (IOException e ) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } finally {

            }
            return checkIn;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {//se ejecuta cada vez que llamamos a un metodo  desde el metodo doingBackground
            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        protected void onPreExecute() {
            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        protected void onPostExecute(CheckIn result) {//se ejecuta cuando termina doingBackgroud()
            progressBar.setVisibility(View.GONE);
        }

        @Override
        protected void onCancelled() {//cuando se cancela el proceso

        }
    }
}//./clase
    
asked by Javier fr 14.12.2016 в 21:14
source

1 answer

1

The best way to implement progress is with a ProgressDialog and Asyntask as in the following example.

    public class GetCoordenadaDir extends AsyncTask<String, String, Map<String,Double>> {
    private Context contexto;
    private ProgressDialog proceso;
    public GetCoordenadaDir(Context context, String Dir) {
            this.contexto = context;

    }



    @Override
    protected  Map<String,Double> doInBackground(String... params) {
       //Tu codigo
    proceso.setMessage("Ya casi terminamos");
    ///MAs codigo
    proceso.setMessage("Se paciente falta poco");
    //Mucho mas codigo
    proceso.setMessage("TERMINAMOS WIII");
        return datos;
    }

    @Override
    protected void onPreExecute() {
            proceso = new ProgressDialog(contexto);
            proceso.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            proceso.setMessage("Carcando Coordenadas Taller");
            proceso.setCancelable(false);
            proceso.show();

    }

    @Override
    protected void onPostExecute(Map<String,Double> doubles) {

            proceso.dismiss();
    }
}

As you realize the progressdialog I instancio in the onPreExecute method that is what your code does not have.

In the same way you can do it with the Progressbar Greetings

    
answered by 14.12.2016 в 23:06