Ferrrmolina Ferrrmolina - 7 months ago 31
SQL Question

Android - SQL query every 1 second for 2 minutes

I'm trying to check a record of a database in real time.
For this, I intend to check every 1 second every 2 minutes.
I've been trying to do the consultations.

The query do with the volley, which maybe it's the most convenient. The problem is that it seems not work the query sequence.

Here my code:

public void SQLQuery(final String hash) {
Handler h = new Handler();
h.postDelayed(new Runnable() {
@Override
public void run() {
int time = 1;
while (time <= 120) {
if (!isAccepted) {
try {
makeRequestAgain(hash);
time++;
Log.d(TAG, String.valueOf(time));
pDialog.setMessage("Segundos restantes: " + time);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
hidePDialog();
Toast.makeText(getActivity(), "Autorización denegada o tiempo de espera agotado.", Toast.LENGTH_LONG).show();
break;
}
}
}
}, 120000);
}

public void makeRequestAgain(final String hash) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, PrepareData.CHECK_REQUEST,
new Response.Listener<String>() {
@Override
public void onResponse(final String response) {
if (response.equalsIgnoreCase(PrepareData.USER_ACCEPT)) {
//
//El user acepto -> OK -> Intent MAP
isAccepted = true;
Toast.makeText(getActivity(), "Autorización OK", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), "Todavia no acepta...", Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Se perdió la conexión con el servidor.", Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put(PrepareData.ID_CONSULTA, hash);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}


enter image description here

Directly, I do not get the message log and the progress dialog is not updated.

What I will be failing?

Thanks in advice.

Edit:

Permissions are OK in the manifest.xml

<uses-permission android:name="android.permission.INTERNET" />


I use this same "makeRequestAgain()" in other .java and run fine, all the request are good, but, this particulary request, doesn't work,.

Answer

I think you can go with Thread. Handler or AsyncTask uses Thread internally. So go with Thread.

Thread t = new Thread(new Runnable(){ ... });
t.start();

So if you want to create a new instant of thread to run again, may be in a loop,

new Thread(t).start(); 

because thread once become a daemon cannot be started again.

Inside the runnable, if you want to update a UI element, you have to do it with runOnUiThread(new Runnable(){...});. Call it inside the Runnable which is in turn inside a Thread.