Reputation:
I have problem with loop. In my opinion this should work, but goes one through the loop. I have to do check availability server and I don't have other ideas.
Server give answer:
{"exist":true}
do {
generateNumber = generate();
getExsistResponse = "http://skidd.herokuapp.com/exist/" + generateNumber;
final StringRequest request = new StringRequest(Request.Method.GET, getExsistResponse, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
existObject exist = new Gson().fromJson(response, existObject.class);
exist.getExist();
String abcd = exist.getExist();
Boolean boolean1 = Boolean.valueOf(abcd);
if (boolean1) {
Log.i("Info", "Pokój: " + abcd);
textView.setText("" + boolean1);
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
} else {
textView.setText("" + boolean1);
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//When an error
}
});
ConnectionManager.getInstance(this).add(request);
//Add the request to the RequestQueue.
}while (boolean1);
and here is my existObject class:
public class existObject {
@SerializedName("exist")
private String checkexist;
public String getExist() {
return checkexist;
}
public void getExist(String name) {
this.checkexist = name;
}
}
Upvotes: 0
Views: 1718
Reputation: 30611
The logic of this approach is not sound. You have made the assumption that the do-while
loop checks the value of boolean1
after each web-service call completes. In reality, what happens is that even before the first web-service call has completed, the do-while
loop has already moved on to the next iteration of the loop, and boolean1
is probably still false, because the first web-service call has not yet been completed. So the do-while
loop breaks.
Realize this: a web-service call is asynchronous. You simply cannot predict how much time it will take to complete, and the time required for each web-service call to complete will always vary. Your do-while
loop, on the other hand, is synchronous: it keeps on creating StringRequest
objects and adding them to the RequestQueue
, and these requests are not executed immediately, so the value of boolean1
may or may not have been set correctly for the next iteration of the do-while
loop.
You need to find another way of making successive network calls such that they are not dependent on each other in this way. If you still want to do it like this and depend on boolean1
, try this:
AsyncTask
and perform an HttpURLConnection
request (and
not a Volley Request
) in its doInBackground()
, and set the value
of boolean1
there.boolean1
is true
, then create a new instance of
the same AsyncTask
in onPostExecute()
and call execute()
to
start the next web-service call.Upvotes: 1