Issue
I have some data stored in a database. In this case the users of an application.
I want to retrieve all their information and put on a layout of my application so I need that the data will be retrieved at onCreate
function of my layout class to display on it when you change to that layout.
I know about AsyncTask
and Volley
to do asynchronous requests to my API but it makes that most times not whole users will be displayed on the layout because they had not been retrieved yet at the moment that the layout is rendered.
I also have searched and it seems that there are some ways (that sometimes seems workarounds) to make both AsyncTask
and Volley
synchronous but they block the UIThread.
I know the difference about the asynchronous
and synchronous
requests and why the second one blocks the application so I have some questions.
- Is it always recommended to use asynchronous requests?
- If synchronous requests are bad, what is used in those cases in which you need that the data that you retrieve from your database will be displayed at the same time the layout is rendered?
- If I want that those data will be available on the whole class of the layout, how can I handle it? I need to display the data on the screen when the layout is rendered but I also want to make some stuff with it so if I try to use it in any place out of
onResponse
method of Volley request I always getnull
. Something as a "preload" of the data.
Thanks in advance!
Solution
Finally, I notice that my problem was about concepts because I thought that you would not be able to use the data retrieved out from onResponse
method of Volley
request.
Finally what I did is to create a global variable on my Fragment and assign the data to that variable when it is fully retrieved. Lets say that I have a String that I want to retrieve.
Then I create the global variable (on the top of the Fragment):
String string = "";
And I create a function that will assign a parameter to this global variable:
public void setString(String string){
this.string = string;
}
To end, after I retrieve the String I call to that function on onResponse
method:
StringRequest jsonArrayRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
//Do stuff to retrieve the String
setString(response); //Assign the string "response" to the global variable via the method.
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("LOG", error.toString());
}
});
If you need to do some stuff with those data you should wait until the data is fully retrieved so you can show a Dialog in the meantime.
I do not know if there is a better way to do this or if this is a bad practice but it is the simplest way I could find by myself.
Answered By - Francisco Romero
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.