Refresh Activity or List (Whichever is better) Android

1

Hi, I have the following activity that creates a list with data brought by php and mysql . How can I make this list update every so often or refresh the activity without having to use the button something like a meta refresh? Thank you very much.

public class PreAsignado extends AppCompatActivity {
ListView listado;
Button Volver;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_pre_asignado);
    listado = (ListView) findViewById(R.id.listView);
    ObtDatos();
    Volver = (Button)findViewById(R.id.btnVolver);
    Volver.setOnClickListener(new View.OnClickListener(){

       @Override
        public void onClick(View v) {
            Intent btnAceptar = new Intent(PreAsignado.this, MainActivity.class);
            startActivity(btnAceptar);
        }
    });
}
@Override
public void onBackPressed() {
}
public void ObtDatos(){
    AsyncHttpClient client = new AsyncHttpClient();
    String url = DIRECCION + "getDataPreAsignados.php";
    SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
    String email = sharedPreferences.getString(Config.EMAIL_SHARED_PREF,"No disponible");
    RequestParams parametros = new RequestParams();
    parametros.put("email", email);
    client.post(url, parametros, new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            if (statusCode == 200){
                CargarLista(obtDatosJSON(new String(responseBody)));
            }
        }
        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
        }
    });
}
public void CargarLista(final ArrayList<Pedido> datos){
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
    for (int i=0;i<datos.size();i++)
    {
        adapter.add(datos.get(i).toString());
    }
    listado.setAdapter(adapter);
    listado.setOnItemClickListener(new AdapterView.OnItemClickListener(){
        public void onItemClick(AdapterView<?> parent, View view, int position, long id){
            Intent intent = new Intent(view.getContext(),Detalle.class);
            intent.putExtra("id",datos.get(position).getId());
            intent.putExtra("barrio",datos.get(position).getBarrio());
            intent.putExtra("direccion",datos.get(position).getDireccion());
            intent.putExtra("pisoDepto",datos.get(position).getPisoDepto());
            intent.putExtra("cliente",datos.get(position).getCliente());
            intent.putExtra("telefono",datos.get(position).getTelefono());
            intent.putExtra("cadete",datos.get(position).getCadete());
            intent.putExtra("pagaCon",datos.get(position).getPagaCon());
            intent.putExtra("estado",datos.get(position).getEstado());
            startActivity(intent);
        }
    }
    );
}
public ArrayList<Pedido> obtDatosJSON(String response){
    ArrayList<Pedido> listadoArray = new ArrayList<Pedido>();
    try{
        JSONArray jsonArray = new JSONArray(response);
        Pedido p;
        for (int i = 0; i < jsonArray.length();i++){
            p = new Pedido(
                    Integer.parseInt( jsonArray.getJSONObject(i).getString("id")),
                    jsonArray.getJSONObject(i).getString("barrio"),
                    jsonArray.getJSONObject(i).getString("direccion"),
                    jsonArray.getJSONObject(i).getString("pisoDepto"),
                    jsonArray.getJSONObject(i).getString("cliente"),
                    jsonArray.getJSONObject(i).getString("telefono"),
                    jsonArray.getJSONObject(i).getString("cadete"),
                    jsonArray.getJSONObject(i).getString("pagaCon"),
                    jsonArray.getJSONObject(i).getString("estado")
            );
            listadoArray.add(p);
        }
    }catch(Exception e){
        e.printStackTrace();
    }
    return listadoArray;
}
}

Sorry but I'm very new with this, I'm looking for onResume as they tell me, I use it and the code gives me an error and when fixing it is like this:

public static final long PERIODO = 60000; // 60 segundos (60 * 1000 millisegundos)
private Handler handler;
private Runnable runnable;



protected void onResume(Bundle savedInstanceState){
    super.onResume();
    handler = new Handler() {
        @Override
        public void publish(LogRecord record) {

        }

        @Override
        public void flush() {

        }

        @Override
        public void close() throws SecurityException {

        }
    };
    runnable = new Runnable(){
        @Override
        public void run(){
            handler.postDelayed(this, PERIODO);
        }
    };
    handler.postDelayed(runnable, PERIODO);
}

postDelayed tells me:

  

Error: (74, 24) error: can not find symbol method   postDelayed (, long)

Please guide me to search to understand what is happening to me and be able to implement it without errors? Thank you very much

    
asked by Juan 18.06.2017 в 01:32
source

2 answers

1

If you have your method to obtain data: ObtDatos() , which in turn calls the load the Activity with the updated data CargarLista() , you can use a handler that the first one should call.

As an example this process would call ObtDatos() every 60000 milliseconds (1 minute)

   final long EXECUTION_TIME = 60000; // 1 minuto

    handler.postDelayed(new Runnable() {

        @Override
        public void run() {

            ObtDatos();

            handler.postDelayed(this, EXECUTION_TIME);
        }
    }, EXECUTION_TIME);
    
answered by 19.06.2017 / 18:59
source
1

I do not know the use case, but usually it is not necessary to refresh periodically a list with which the user interacts. Normally the update is done because an event occurs, such as when the user returns to the screen where the list is.

Refresh the list from the Internet periodically, incurs battery charges, and may also consume part of the data package without the user knowing or needing it.

If it were sufficient for your app to refresh when the user interacts with the list, it would be just a matter of doing the json drop and the%% change set de datos of the list within the adapter method of onResume() .

If you manage Activity it can be done in Fragments or in onResume() depending on which other dependencies can have the onActivityAcreate() with the Fragment that contains it.

Another alternative, which I think goes beyond the context of the question, is that if the update depends on events that occur on the server, it would be possible to use a Push framework such as Firebase Cloud Messaging (FCM), only or in set with OneSignal or Urbanairship. These products allow you to receive a "signal" from your server when the app should update some data.

EDITION 1

Having said the above, if you really think you need a periodic refresh while the user is in the Activity, you can implement it with a Handler that is activated in Activity and deactivated in onResume() .

public static final long PERIODO = 60000; // 60 segundos (60 * 1000 millisegundos)
private Handler handler;
private Runnable runnable;

In onResume ():

handler = new Handler();
runnable = new Runnable(){
    @Override
    public void run(){
         <Bajar los datos y refrescar la lista>
         handler.postDelayed(this, PERIODO);
    }
}
handler.postDelayed(runnable, PERIODO);

On onPause ():

handler.removeCallbacks(runnable);
    
answered by 18.06.2017 в 02:16