0
    btnIniciar = (Button)findViewById(R.id.btnempezar);
    Ritmo = (TextView)findViewById(R.id.BPM);
    Temperatura = (TextView)findViewById(R.id.temperatura);
    Tiempo = (TextView)findViewById(R.id.tiempo);
    Chipid = (EditText)findViewById(R.id.chipid);
    telefonop = (EditText)findViewById(R.id.numeroPropio);
    telefonoc = (EditText)findViewById(R.id.contacto);
    prueba = (TextView)findViewById(R.id.prueba);

    btnIniciar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            new datosInvitado.ConsultarDatos().execute("http://185.125.110.65/Android/consultaultimodato.php?Chipid="+Chipid.getText().toString());
        }
    });
}

private class ConsultarDatos extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {

        // params comes from the execute() call: params[0] is the url.
        try {
            return downloadUrl(urls[0]);
        } catch (IOException e) {
            return "Unable to retrieve web page. URL may be invalid.";
        }
    }

    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {

        JSONArray ja = null;
        try {
            ja = new JSONArray(result);
            Ritmo.setText(ja.getString(0));
            Temperatura.setText(ja.getString(1));
            Tiempo.setText(ja.getString(2));

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}

private String downloadUrl(String myurl) throws IOException {
    Log.i("URL",""+myurl);
    myurl = myurl.replace(" ","%20");
    InputStream is = null;
    // Only display the first 500 characters of the retrieved
    // web page content.
    int len = 500;

    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        int response = conn.getResponseCode();
        Log.d("respuesta", "The response is: " + response);
        is = conn.getInputStream();

        // Convert the InputStream into a string
        String contentAsString = readIt(is, len);
        return contentAsString;

        // Makes sure that the InputStream is closed after the app is
        // finished using it.
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
    Reader reader = null;
    reader = new InputStreamReader(stream, "UTF-8");
    char[] buffer = new char[len];
    reader.read(buffer);
    return new String(buffer);
}
public void rLogin(View vista){
    Intent intento = new Intent(this,Login.class);
    startActivity(intento);
}

}

Actualmente me encuentro desarrollando una aplicación que consulta información en una base de datos MySQL, ya puedo recibir los datos y los paso a las vistas que tengo en mi diseño, cuando oprimo un botón se realiza la consulta a la base de datos, se reciben los datos y los asigno a las vistas (TextView) que tengo, ya puedo visualizar la información, sin embargo lo que aún no puedo realizar es que esta tarea se repita cada determinado tiempo, ya que en la base de datos se inserta información cada 5 segundos, la idea es ir a la par con la base de datos que cada 5 segundos pueda repetir la tarea y obtener los últimos datos que se insertaron en la base de datos, apreciaría cualquier consejo y gracias de antemano

1 respuesta 1

0

Intenta utilizando Handlers. Esto te permite ejecutar un algoritmo segun el tiempo especificado. Solo tienes que hacer recursion con el handler y tendras una llamada cada 5 segundos:

final int duracion = 5000;
final Handler handler = new Handler(); 
Runnable runnable = new Runnable() { 

    @Override 
    public void run() { 
        try{
            new datosInvitado.ConsultarDatos().execute("http://185.125.110.65/Android/consultaultimodato.php?Chipid="+Chipid.getText().toString());
        }
        catch (Exception e) {
          // manejas la excepcion en caso de error.
        }
        finally{
            // ejecutamos otra vez el handlers
            handler.postDelayed(this, duracion); 
        }
    } 
}; 

handler.postDelayed(runnable, duracion); // iniciamos el intervalo

Aqui el codigo completo al momento de dar clic:

final int duracion = 5000;
final Handler handler = new Handler(); 

btnIniciar.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        Runnable runnable = new Runnable() { 

            @Override 
            public void run() { 
                try{
                    new datosInvitado.ConsultarDatos().execute("http://185.125.110.65/Android/consultaultimodato.php?Chipid="+Chipid.getText().toString());
                }
                catch (Exception e) {
                  // manejas la excepcion en caso de error.
                }
                finally{
                    // ejecutamos otra vez el handlers
                    handler.postDelayed(this, duracion); 
                }
            } 
        }; 

        handler.postDelayed(runnable, duracion); // iniciamos el intervalo
    }
});
9
  • Excelente amigo muchas gracias pondré en practica tu consejo, solo me quedo una duda ¿cómo podría manejar esto al momento de oprimir el botón? gracias por tu ayuda de antemano.
    – Angelc
    el 17 abr. 2018 a las 1:47
  • Te refieres a ejecutar el codigo al momento de dar click?
    – Einer
    el 17 abr. 2018 a las 1:54
  • Exacto, a eso me refiero amigo.
    – Angelc
    el 17 abr. 2018 a las 3:00
  • Acabo de actualizar agregando el codigo completo @Angelc
    – Einer
    el 17 abr. 2018 a las 11:15
  • 1
    Amigo me funciono de maravillas, muchísimas gracias.
    – Angelc
    el 18 abr. 2018 a las 3:10

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.