Update UI from an asynctask

0

from an activity where I have a simple listview of three items and each one has a counter (set) for example: item1 has 2 units item2 has 3 units item3 has 4 units. That number of units is a value set by the result of the asyntask

    public class actMenu extends Activity{
    private ListView m_listview_listas;
// este es mi listado  que luego estoy llenando en el oncreate del activity por medio de un adapter. (funciona correcto)
    }

Listview load method

customAdapter = new CustomCursorAdapter(actMenu.this, row2, valoresGenerales.isMenuOpciones);
m_listview_listas.setAdapter(customAdapter);

// filled the list by the CustomCursorAdapter adapter

method that calls asyntask

private void llamar (boolean withPeriod){

TimerCheckNew (m_handler, m_activity, m_context);

    final int delayMillis = 100; // delay for 0.1 seconds
    final long defaultPeriod = TimeUnit.MINUTES.toMillis( 5 );
    valoresGenerales.mTimerSincro = new Timer();
    if (withPeriod)
    {
        String strPeriod = valoresGenerales.sharedPrefs.getString("pref_sync_minutes", "-1");
        long period = (strPeriod.equals("-1")) ? defaultPeriod : TimeUnit.MINUTES.toMillis( Integer.valueOf(strPeriod) );


        valoresGenerales.mTimerSincroManten.scheduleAtFixedRate(valoresGenerales.timerCheckNewMaintenances,
                delayMillis, period);
    } else
    {
        valoresGenerales.mTimerSincroManten.schedule(valoresGenerales.timerCheckNewMaintenances, delayMillis);
    }
}

TimerCheckNew class

public class TimerCheckNew extends TimerTask {
   private Handler m_handler = null;
   private Activity m_activity;
   private Context m_context;

   public TimerCheckNewMaintenances(Handler handler, Activity activity, Context context
         ) {
      m_handler = handler;
      m_activity = activity;
      m_context = context;
   }

   private Runnable runnable = new Runnable() {
      public void run() {

         final String methodName = "run";

                     valoresGenerales.gettingSincroManten = true;


                     JSONObject jsonParam = new JSONObject();
                     try{
                        jsonParam.put( "workerId", valoresGenerales.beanUsuario.operario );



                     }
                     catch( JSONException e ){
                        Log.e( getClass().getName(), e.getMessage() );
                     }

                     new DownloadMaintenancesTask(m_handler, m_activity, m_context).execute( jsonParam.toString() );

                  } 
      }
   };

   public void run() {
      m_handler.post(runnable);
   }

}

DownloadMaintenancesTask class

public class DownloadMaintenancesTask extends DownloadTask {



    public DownloadMaintenancesTask(Handler handler, Activity activity, Context context) {


        super(handler, activity, context);
    }

    protected String getProgressTitle() {
        return valoresGenerales.appContext.getString(R.string.msj_sincronizando_mantenimientos);
    }

    protected String getProgressMessage() {
        return valoresGenerales.appContext.getString(R.string.msj_por_favor_espere);
    }


    @Override
    protected String doInBackground(String... params) {
        if (!FunctionsUtil.isOnline()) {

            publishProgress("updateView");
        // aca ya tengo los valores. Pero como actualizo la vista.
        } catch (JSONException e) {
            msg = e.getMessage();
            Log.e(getClass().getName(), msg);
        }

        return msg;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);


    }


}

DownloadTask class

    public abstract class DownloadTask extends AsyncTask<String, String, String>
    {
        protected Activity parentActivity = null;
        protected Context context = null;
        protected Handler handler = null;
        protected ProgressDialog progressDlg = null;


        public DownloadTask(Handler handler, Activity activity, Context context)
        {
            this.handler = handler;
            this.parentActivity = activity;
            this.context = context;     
        }

        protected abstract String getProgressTitle();   
        protected abstract String getProgressMessage();
        protected boolean getClearTable(){
            return false;
        }

        @Override
        protected void onPreExecute()
        {
            try
            {
                // CERRAMOS EL DIALOGO SI ESTA ACTIVO
                if (progressDlg != null && progressDlg.isShowing())
                    progressDlg.dismiss();

                progressDlg = new ProgressDialog(parentActivity);
                if (progressDlg != null)
                {
                    progressDlg.setTitle(getProgressTitle());
                    progressDlg.setMessage(getProgressMessage());

                    progressDlg.setCancelable(false);
                    progressDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);

                    progressDlg.show();
                }

            } catch (Exception ex)
            {
                FunctionsUtil.generaLog(TipoLog.Exception, "DownloadTask", "onPreExecute", logger, ex);
            }
        }   

        @Override
        protected void onPostExecute(String result)
        {
            super.onPostExecute(result);        
            if (progressDlg != null && progressDlg.isShowing()){
                progressDlg.dismiss();
                progressDlg = null;
            }
        }   

        @Override
        protected void onProgressUpdate(String... progress)
        {
            if (progressDlg != null)
            {
                progressDlg.setMessage(progress[0]);
            }
            if(progress[0].equals("updateView"))
            {

                parentActivity.recreate();  
// refresca pero todo el activity . solo necesito volver a cargar el listado
            }
        }   

        protected InputStream sendRequest( List<PropertyInfo> properties, String webMethod )
        {       
            publishProgress(valoresGenerales.appContext.getString(R.string.str_waiting_for_server_response));

            InputStream responseXml = null; 
            WSTransport transport = new WSTransport( properties, webMethod );
            if( transport != null ){
                try{
                    transport.send();
                    responseXml = transport.getResponse();
                }
                catch( Exception e ){
                    Log.e(getClass().getName(), e.getMessage());
                }
            }       
            return responseXml;
        }   

        protected final boolean processResponse( final InputStream result ) throws Exception{

            publishProgress( valoresGenerales.appContext.getString(R.string.str_procesing_response));

            boolean transactionOk = true;
            if (result != null)
            {
                DatabaseMgr dbMgr = new DatabaseMgr(context);
                try{
                    if (dbMgr != null)
                    {
                        dbMgr.open();
                        dbMgr.beginTransaction();           
                        XmlResponseParser parser = new XmlResponseParser(result);
                        if (parser != null)
                        {
                            parser.parse( dbMgr, getClearTable() );
                        }               
                        dbMgr.setTransactionSuccessful();
                    }
                }
                catch( Exception ex ){
                    Log.e(getClass().getName(), ex.getMessage());
                    transactionOk = false;
                }

                dbMgr.endTransaction();
                dbMgr.close();

                //FunctionsUtil.contadorDeRegistros(context);
            }
            else{
                throw new Exception( String.format( "%s: No response recieved from server", getClass().getName() ));
            }

            return transactionOk;
        }

        protected List<PropertyInfo> getRequestProperties( final String jsonProperties ){           

            List<PropertyInfo> properties = null;
            try{
                JSONObject object = new JSONObject( jsonProperties );

                JSONArray names = object.names();
                JSONArray values = object.toJSONArray(names);

                properties = new ArrayList<>();
                if( properties != null ){

                    for( int i = 0; i < names.length(); i++ ){

                        PropertyInfo piRowVersion = new PropertyInfo();
                        piRowVersion.name = names.getString(i);
                        piRowVersion.setValue(values.get(i));
                        properties.add(piRowVersion);
                    }
                }
            }
            catch( JSONException e ){
                Log.e( getClass().getName(), e.getMessage() );
            }

            return properties;
        }   
    }

I have not been able to make it refresh only the list but if all the activity .. using

parentActivity.recreate();  que esta en la clase DownloadTask método onProgressUpdate 

how can I achieve it. Any ideas?

    
asked by Gerard Cáceres 18.06.2018 в 22:24
source

0 answers