Reputation: 123
I have a JSON request looking like this:
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
url,
(String) null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
roomArray = parseRoomsResponse(response);
callback.onSuccess(roomArray);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}
This request is inside the onCreateView()
method, and my parseRoomsResponse()
method returns me an ArrayList
that I wish to work with inside onCreateView()
, so what is the proper way of doing this thing?
Upvotes: 4
Views: 118
Reputation: 5411
I know its ok, i must handle everithing inside onSuccess inner class, is there some way of getting values to onCreateView? – Zoltan Kurtyak
Ahh.. I see you issue now.
The problem here is that a Request takes an unknown amount of time to return a Response, so Volley makes these requests asynchronously for you rather than lock up your UI thread.
So if you make a Request in onCreateView
, it's unlikely that you'll still be in onCreateView
when you get the response.
You may need to rethink the flow of your code. If your fragment's view depends on the Response from a request, then you should probably make sure you do the Request and obtain the Response before you create your Fragment's view.
A typical approach to this problem is just use place holder values until the response is received. For example:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_layout, container, false);
...
EditText myEditText = (EditText) rootView.findViewById(R.id.response_dependent_edittext);
myEditText.setText("Loading Data");
ImageView myImageView = (ImageView) rootView.findViewById(R.id.response_dependent_imageview);
myImageView.setImageResource(R.drawable.image_placeholder);
...
return rootView;
}
Then you can create an updateViews method;
private void updateViews(ArrayList<MyArrayType> myParsedArray) {
// Extract relevant data from the array
...
// Replace the place holders in the relevant views
EditText myEditText = (EditText) getView().findViewById(R.id.response_dependent_edittext);
myEditText.setText(stringFromParsedArray);
ImageView myImageView = (ImageView) getView().findViewById(R.id.response_dependent_imageview);
myImageView.setImageDrawable(drawableFromParsedArray);
}
and call it from your request's onResponse
method:
@Override
public void onResponse(JSONObject response) {
myParsedArray = parseResponse(response);
updateViews(myParsedResponse);
...
}
Upvotes: 1