Search code examples
androidandroid-asynctaskprogressdialogupdating

Updating Progressdialog


i have problem with progressdialog to the, i want updating my progressdialog while duration of the connection.

This is my progressdialog

Pro = new ProgressDialog(getParent());
    Pro.setMessage("Enviando");
    Pro.setIndeterminate(false);
    Pro.setMax(100);
    Pro.setCancelable(false);
    Pro.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

this my asynctask

private class NuevoPostVideo extends AsyncTask<String, Integer, String>{



     @Override
    protected String doInBackground(String... params) {
         objAcceso = new AccesoBd();
         String jsRes= "";

         SharedPreferences userDetails = getParent().getSharedPreferences("MisPreferencias", MODE_PRIVATE);

        try{

            File f = new  File(sDireccionFoto); 

            FileBody bin = new FileBody(f);

            StringBody  from = new StringBody( Integer.toString(userDetails.getInt("Id",0)));

          StringBody id_recurso = new StringBody(Integer.toString(idEvento));
          StringBody titulo_body = new StringBody(txtVTitulo.getText().toString());
          StringBody ficha = new StringBody("null");


         MultipartEntity reqEntity = new MultipartEntity();
         reqEntity.addPart("imageFile", bin);
         reqEntity.addPart("from",from);
         reqEntity.addPart("idrecurso",id_recurso);
         reqEntity.addPart("titulo", titulo_body);
         reqEntity.addPart("ficha", ficha);


        objAcceso.conxDatosInPost(params[0],reqEntity);
        jsRes="ok";

    }
    catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();

     }finally{return jsRes;}

        }
     @Override
     protected void onPostExecute( String result) {


         if (result.equals("ok")){

         SharedPreferences userDetails = getParent().getSharedPreferences("MisPreferencias", MODE_PRIVATE);
         DetalleEvento objd = new DetalleEvento();
         objd.setTipo(1);
         objd.setFecha(objAcceso.FechaActualinglesa());
         objd.setTituloPost(sTituloPost);
         objd.setImagen(btmImagenElegida);
         objd.setUrl(sDireccionFoto);
         objd.setAutor(userDetails.getString("Nombre","Usted"));



         objAdapterDetalles.arrayDatos.add(0,objd);

         objAdapterDetalles.notifyDataSetChanged();
         lstDatos.setSelection(1);
         dOpciones.dismiss();
         dHacerVideo.dismiss();

         }
            Pro.dismiss();
            prgVProgreso.setVisibility(View.INVISIBLE);
        }
     @Override
        protected void onPreExecute() {

            //prgVProgreso.setVisibility(View.VISIBLE);
        Pro.show();
            //Pro.incrementProgressBy(10);


    }
     @Override
      public void onProgressUpdate(Integer... args){
          Pro.setProgress(args[0]);
                    } 




 }

this my function of conexion "Look at this line of my doinbhackgroud" (objAcceso.conxDatosInPost(params[0],reqEntity); )

 public  String conxDatosInPost(String Direccion, MultipartEntity Parametros) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = ClienteHttp();
            HttpPost request = new HttpPost(Direccion);
            request.setEntity(Parametros);
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            } 
            in.close();

            String result = sb.toString();
            Log.d("El resultado de cnxposin es :-----------  ",  result +"fn");

            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

¿as I can do to update my progress dialog While the connection lasts ?

UPDATE

I have problems to calculate the size of the file to insert (video in this case) and to see the progress of the upload to the server at each times

find not the way to do this

I would like to know if there was the possibility of some listener progresslistener style?

please could help me or give me a hint


Solution

  • ultimately solve my problem as follows

    this is how my code is

    public class NuevoPostVideoConProgreso extends AsyncTask<String, Integer, String>{
    
                 ProgressDialog dialogProgreso;
                long totalSize;
    
                     @Override
                    protected String doInBackground(String... params) {
                         objAcceso = new AccesoBd();
                         String res = "";
                         SharedPreferences userDetails = getParent().getSharedPreferences("MisPreferencias", MODE_PRIVATE);
                        try{
    
    
                        CMultipartContador objconSub = new CMultipartContador(new CMultipartContador.ProgressListener() {
    
                            @Override
                            public void transferred(long num) {
                                // TODO Auto-generated method stub
    
                                float antes = (float)(num /(float) totalSize);
                                float despues =(float)(antes * 100);
    
                                int numero = (int) despues;
    
    
                                publishProgress(numero);//(int) ((num /(float) totalSize) * 100));
                            }
                        } );
    
                            File f = new  File(sDireccionFoto); 
    
                            FileBody bin = new FileBody(f);
    
                            StringBody  from = new StringBody( Integer.toString(userDetails.getInt("Id",0)));
    
                          StringBody id_recurso = new StringBody(Integer.toString(idEvento));
                          StringBody titulo_body = new StringBody(txtVTitulo.getText().toString());
                          StringBody ficha = new StringBody("null");
    
    
                        // MultipartEntity reqEntity = new MultipartEntity();
                         objconSub.addPart("imageFile", bin);
                         objconSub.addPart("from",from);
                         objconSub.addPart("idrecurso",id_recurso);
                         objconSub.addPart("titulo", titulo_body);
                         objconSub.addPart("ficha", ficha);
    
                        totalSize= objconSub.getContentLength();
                       // dialogProgreso.setMax((int)totalSize);
    
                        objAcceso.conxDatosInPostAsynctask(params[0],objconSub);
    
    
    
                    dialogProgreso.setProgress(100);
    
                        res= "ok";
    
    
    
    
    
                    }
                    catch (Exception e) {
                        // TODO: handle exception
                        e.printStackTrace();
    
                     }finally{return res;}
    
                        }
                     @Override
                     protected void onPostExecute( String result) {
    
                         dialogProgreso.setProgress(100);
                         dialogProgreso.dismiss();
                         dOpciones.dismiss();
                         dHacerVideo.dismiss();
    
    
                         LlenarEvento();
    
    
    
    
                     }
                     @Override
                        protected void onPreExecute() {
                         dialogProgreso = new ProgressDialog(getParent());
                            dialogProgreso.setMessage("Subiendo...");
                            dialogProgreso.setIndeterminate(false);
                            //dialogProgreso.setMax(100);
                            dialogProgreso.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                            //dialogProgreso.setProgress(0);
                            dialogProgreso.setCancelable(false);
                            dialogProgreso.show();
                            //dialogProgreso.setProgress(3);
    
    
                    }
                     @Override
                      public void onProgressUpdate(Integer... args){
                          dialogProgreso.setProgress(args[0]);
                                    } 
    
    
    
    
                 }
    
                private ImageView aniadirImagen(Bitmap btmi){
                    ImageView img= new ImageView(getParent());
    
                    img.setImageBitmap(btmi);
                    btmi.recycle();
                    return img;
                }
    

    and this is my new class

    public class CMultipartContador extends MultipartEntity {
    
    
    private final ProgressListener listener;
    
    public CMultipartContador(final ProgressListener listener)
    {
        super();
        this.listener = listener;
    }
    
    public CMultipartContador(final HttpMultipartMode mode, final ProgressListener listener)
    {
        super(mode);
        this.listener = listener;
    }
    
    public CMultipartContador(HttpMultipartMode mode, final String boundary, final Charset charset, final ProgressListener listener)
    {
        super(mode, boundary, charset);
        this.listener = listener;
    }
    
    @Override
    public void writeTo(final OutputStream outstream) throws IOException
    {
        super.writeTo(new CountingOutputStream(outstream, this.listener));
    }
    
    public static interface ProgressListener
    {
        void transferred(long num);
    }
    
    public static class CountingOutputStream extends FilterOutputStream
    {
    
        private final ProgressListener listener;
        private long transferred;
    
        public CountingOutputStream(final OutputStream out, final ProgressListener listener)
        {
            super(out);
            this.listener = listener;
            this.transferred = 0;
        }
    
        public void write(byte[] b, int off, int len) throws IOException
        {
            out.write(b, off, len);
            this.transferred += len;
            this.listener.transferred(this.transferred);
        }
    
        public void write(int b) throws IOException
        {
            out.write(b);
            this.transferred++;
            this.listener.transferred(this.transferred);
        }
    }