I am making an Android app and I need to make a JSONObjectRequest to get a parameter (logo
) from a package.json
in a github repository.
This is the method where I make the JSON request
public void askLogoPath(String url) {
JsonObjectRequest req = new JsonObjectRequest(url,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
if (response.has("logo"))
Global.getInstance().setLogo(response.getString("logo"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
// Adding request to request queue
QueueController.getInstance().addToRequestQueue(req);
}
I have defined a variable (logo
) in Global
class that follows Singleton pattern, so I can access it everywhere in my program. After making this request, I want to set a variable with the value of logo.
This is the piece of code where I call the previous function.
if (full_name != null) {
String url = "https://raw.githubusercontent.com/" + full_name + "/master/";
this.askLogoPath(url + "package.json");
this.setLogoPath(Global.getInstance().getLogo());
}
I have noticed that the onResponse
part is the last one to be executed, so when I do setLogoPath(Global.getInstance.getLogo())
logo is still null, so I can't set logoPath
in the previous line. I would like to wait until this is executed, so it won't be null.
Is there any way to make it synchronous so I can do this?
Thank you very much
It was solved by adding a callback. When the JSON
request receives a response, it calls the onSuccess()
method of the callback function, and in the main function the rest of the code is inside this onSuccess()
method.