Lambda Expression Returning Null Android
Solution 1:
First of all, Lambda Expression is just a anonymous class implementation, it was design to be used as a method or class argument and solve shadowing issues of anonymous class.
So in your case, you don't need it at all, just simply implement CoordinatesToAddressInterface
interface as named class as usual.
Second, you used Volley wrong, the first lambda you provided to StringRequest
, hereafter will be call response callback, is going to be called when HTTP request finish but the return statement
return getLocation();
will return null immediately before your setLocation(location)
or even your response callback ever get executed, that why you got null every time you call convert()
, though you can still see log that you print because the response callback will be executed anyway (assume that request is success).
To use response callback correctly, you have to update your UI inside callback, pretty much like this
publicclassMyAdapterextendsRecyclerView.Adapter<MyAdapter.MyViewHolder> {
publicstatic final StringTAG = "MyAdapter";
privateRequestQueue mQueue;
publicMyAdapter(Context context) {
this.mQueue = Volley.newRequestQueue(context);
}
publicRequestQueuegetMyAdapterRequestQueue() {
returnthis.mQueue;
}
...
@OverridepublicvoidonBindViewHolder(@NonNull final MyViewHolder holder, int position) {
String url ="some url";
StringRequest stringRequest = newStringRequest(Request.Method.GET, url,
(String response) -> {
try {
JSONObject jsonObject = newJSONObject(response);
JSONArray destinations = jsonObject.getJSONArray("destination_addresses");
Log.d(TAG, "GETRequest: JSON Object: "+destinations.toString());
String location = destinations.toString();
Log.d(TAG, "Location: "+location);
// update UI
holder.mTextView.setText(location);
} catch (JSONException e) {
e.printStackTrace();
}
}, error -> Log.d(TAG, "onErrorResponse: That didn't work!"));
stringRequest.setTag(TAG);
mQueue.add(stringRequest);
}
Of course, you can edit your interface's method signature and make your adapter implement that interface (I would rather do it this way though) but the point is that you have to process asynchronous results in callback method, never expect asynchronous operation's callback to finish before your next lines of code.
RequestQueue
shouldn't be created per-request since it manages internal state that help you make request faster (caching), you can also cancel requests too in an event like phone rotation and your will get destroy, in this case, just call cancel method in Activity/Fragment's onStop()
@OverrideprotectedvoidonStop() {
super.onStop();
if (myAdapter.getMyAdapterRequestQueue() != null) {
myAdapter.getMyAdapterRequestQueue().cancelAll(MyAdapter.TAG);
}
}
Response callback won't be called after you cancel request.
Post a Comment for "Lambda Expression Returning Null Android"