Android: ProgressBar on AsyncTask

0

I have a problem, what happens is that I have a AsyncTask and I want to put a ProgressBar but what happens is that AsyncTask I have it independent (in a class I only have that AsyncTask ) I tried to put the ProgressBar but it does not fit.

This is my class

public class SearchData extends AsyncTask<Object, Object, CheckIn> {//creo una atrea en segundo plano

    @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(Object... values) {//se ejecuta cada vez que llamamos a un metodo  desde el metodo doingBackground

    }

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected void onPostExecute(CheckIn result) {//se ejecuta cuando termina doingBackgroud()

    }

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

    }
}//./clase
    
asked by Javier fr 14.12.2016 в 16:09
source

3 answers

1

I recommend that you go through the ProgressBar parameter since if you have it separated

public class SearchData extends AsyncTask<Object, Integer, CheckIn> {
    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
    }
}

And from the Activity that you call this task, something like this:

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

progressBar.setProgress (0);

new TuClaseAsyncTask().execute(progressBar);

Since you have this separated from your Activity create the method setProgressBar , if you have more elements that you would like to initialize (visual elements I say) I would recommend you always create them within your asynchronous class and add a set method. The second option that I gave you to call your task, is just as valid only that I would change this:

@Override
protected void onProgressUpdate(Integer... values) {
    super.onProgressUpdate(values[0]);
}
    
answered by 14.12.2016 в 16:24
0

Here I call my asynchronous task

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

                    int parameters[] = {inputData};
                    CheckIn checkIn = null;//hago una instancia de DataCheckIn y la guado en una variable
                    try {
                        checkIn = new SearchData().execute(parameters, progressBar).get();//le paso el folio como parametro a SearchData
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }

My ProgressBar in activity_main.xml

<ProgressBar
            android:id="@+id/progress_bar"
            android:layout_width="200dp"
            android:layout_height="200dp"
            android:indeterminate="false"
            android:progressDrawable="@drawable/circular_progress_bar"
            android:background="@drawable/circle_shape"
            style="?android:attr/progressBarStyleHorizontal"
            android:max="100"
            android:progress="65" />

Design of the ProgressBar in Drawable circle_shape.xml

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

<solid android:color="#CCC" />

As I receive it and put it on my AsyncTask

public class SearchData extends AsyncTask<Object, Integer, CheckIn> {//creo una atrea en segundo plano

ProgressBar bar;

public void setProgressBar(ProgressBar bar) {
    this.bar = bar;
}
    
answered by 14.12.2016 в 17:05
0

I'm working on the same thing, and it's functional. I share:

// Cargar el archivo en el servidor
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
    @Override
    protected void onPreExecute() {
        progressBar.setProgress(0);         // Establecer la ProgressBar a 0%
        txtSubido.setText("0");
        super.onPreExecute();
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        progressBar.setVisibility(View.VISIBLE);    // Hacer visible la barra de progreso
        progressBar.setProgress(progress[0]);       // Actualización del valor de la barra de progreso
        txtPercentage.setText(String.format("%s%%", String.valueOf(progress[0])));  // Actualizando el valor porcentual

        txtUnidad.setText(R.string.unidad_kb);
        int divisorUnidad = 1024;

        if(totalSize/(divisorUnidad*1024) > 1) {
            txtUnidad.setText(R.string.unidad_mb);
            divisorUnidad = divisorUnidad*1024;
        }

        txtTotal.setText(String.format(Locale.getDefault(),"%,.2f", (float) totalSize/divisorUnidad));

        try {
            txtSubido.setText(String.format(Locale.getDefault(), "%,.2f", (float) progress[0] * Float.parseFloat("" + txtTotal.getText().toString().replace(",", "")) / 100));
            llTamaño.setVisibility(View.VISIBLE);
        }catch (Exception e){
            e.printStackTrace();
            txtSubido.setText("?");
            llTamaño.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    protected String doInBackground(Void... params) {
        return uploadFile();
    }

    @SuppressWarnings("deprecation")
    private String uploadFile() {
        String responseString;

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost; // = new HttpPost(Config.FILE_UPLOAD_URL);   //Configuración del servidor URL
        //Log.d(TAG, "url0: "+Config.FILE_UPLOAD_URL);
        //Log.d(TAG, "url1: "+String.valueOf(url1Rb.getText()));
        //Log.d(TAG, "url2: "+String.valueOf(url2Rb.getText()));

        if(url1Rb.isChecked())
            httppost = new HttpPost(String.valueOf(url1Rb.getText()));  //Configuración del servidor URL
        else
            httppost = new HttpPost(String.valueOf(url2Rb.getText()));  //Configuración del servidor URL

        try {
            AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
                    new AndroidMultiPartEntity.ProgressListener() {
                        @Override
                        public void transferred(long num) {
                            publishProgress((int) ((num / (float) totalSize) * 100));
                        }
                    });

            File sourceFile = new File(filePath);
            // Adición de datos de archivo al cuerpo http
            entity.addPart("file", new FileBody(sourceFile));   //en ambos sv, se espera la imagen con el parametro "file"

            totalSize = entity.getContentLength();  //Largo total, para transformarlo a porcentual
            httppost.setEntity(entity);
            HttpResponse response = httpclient.execute(httppost);   // Hacer una llamada al servidor
            HttpEntity r_entity = response.getEntity();

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                responseString = EntityUtils.toString(r_entity); //Respuesta del servidor
            } else {
                responseString = "¡Se produjo un error! Código de estado Http: " + statusCode;
            }

        } catch (Exception e) {
            responseString = e.toString();
        }
        return responseString;
    }

    @Override
    protected void onPostExecute(String result) {
        Log.d(TAG, "Respuesta del servidor: " + result);
        showAlert(result);
        btnUpload.setEnabled(true); //se habilita al finalizar
        btnUpload.setTextColor(ContextCompat.getColor(UploadActivity.this, android.R.color.white));
        super.onPostExecute(result);
    }
}

Tell me if you do not understand something, I have no problem sharing more

    
answered by 14.12.2016 в 19:57