Lambda表达式返回null android

问题描述 投票:0回答:1

我正在编写一个lambda表达式,将给定的纬度和经度转换为一个地址。该表达式应该将坐标作为参数并返回其相应的地址。但是,返回的值为null。以下是我的课程:

public class LambdaDeclarations {

String loc;

private static final String TAG = "LambdaDeclarations";

public CoordinatesToAddressInterface convert = (latitude, longitude, context) -> {
    RequestQueue queue = Volley.newRequestQueue(context);

    Log.d(TAG, "onCreate: Requesting: Lat: "+latitude+" Lon: "+longitude);
    String url ="https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins="+latitude+","+longitude+"&destinations="+latitude+","+longitude+"&key=AIzaSyCdKSW0glin4h9sGYa_3hj0L83zI0NsNRo";
    // Request a string response from the provided URL.
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            (String response) -> {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    JSONArray destinations = jsonObject.getJSONArray("destination_addresses");
                    Log.d(TAG, "GETRequest: JSON Object: "+destinations.toString());
                    String location = destinations.toString();
                    Log.d(TAG, "Location: "+location);
                    setLocation(location);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }, error -> Log.d(TAG, "onErrorResponse: That didn't work!"));
    queue.add(stringRequest);
    return getLocation();
};


public String getLocation() {
    return loc;
}

public void setLocation(String location) {
    this.loc = location;
    }
}

以下是logcat的输出:

09-16 10:31:09.160 26525-26525/com.rmit.tejas.mad_foodtruck_2 D/LambdaDeclarations: GETRequest: JSON Object: ["77 State Route 32, West Melbourne VIC 3003, Australia"]
Location: ["77 State Route 32, West Melbourne VIC 3003, Australia"]
09-16 10:31:09.176 26525-26525/com.rmit.tejas.mad_foodtruck_2 D/LambdaDeclarations: GETRequest: JSON Object: ["111 Adderley St, West Melbourne VIC 3003, Australia"]
Location: ["111 Adderley St, West Melbourne VIC 3003, Australia"]
09-16 10:31:09.177 26525-26525/com.rmit.tejas.mad_foodtruck_2 D/LambdaDeclarations: GETRequest: JSON Object: ["4\/326 William St, Melbourne VIC 3000, Australia"]
Location: ["4\/326 William St, Melbourne VIC 3000, Australia"]

以下是我的用法:

myViewHolder.textView3.setText("Location: i->"+i+" add: "+l.convert.toAddress(trackingInfos.get(i).getLatitude(),trackingInfos.get(i).getLongitude(),context));

l是类LambdaDeclarations的一个对象,以下是相关的接口:

public interface CoordinatesToAddressInterface {
String toAddress(double latitude, double longitude, Context context);
}

当我尝试从相关适配器打印坐标时,它们将被正确打印。所以位置设置正确,但是当我尝试从另一个类访问它时,它显示了字符串的空值。你能否建议另一种从表达式中提取位置的方法?

android lambda google-distancematrix-api
1个回答
1
投票

首先,Lambda Expression只是一个匿名类实现,它被设计为用作方法或类参数并解决匿名类的阴影问题。 因此,在您的情况下,您根本不需要它,只需像往常一样简单地将CoordinatesToAddressInterface接口实现为命名类。

第二,你使用了Volley错误,你提供给StringRequest的第一个lambda,以后将是call response response,当HTTP请求完成但是返回语句时将被调用

return getLocation();

将在你的setLocation(location)甚至你的响应回调被执行之前立即返回null,这就是为什么每次调用convert()时都为null,尽管你仍然可以看到你打印的日志,因为无论如何都会执行响应回调(假设请求成功)。

要正确使用响应回调,您必须在回调内更新UI,就像这样

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
public static final String TAG = "MyAdapter";
private RequestQueue mQueue;

public MyAdapter(Context context) {
    this.mQueue = Volley.newRequestQueue(context);
}

public RequestQueue getMyAdapterRequestQueue() {
    return this.mQueue;
}

    ...

@Override
public void onBindViewHolder(@NonNull final MyViewHolder holder, int position) {
    String url ="some url";

    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            (String response) -> {
                try {
                    JSONObject jsonObject = new JSONObject(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);
}

当然,你可以编辑你的接口的方法签名,并使你的适配器实现该接口(我宁愿这样做)但重点是你必须在回调方法中处理异步结果,永远不要指望异步操作的回调完成之前你的下一行代码。

RequestQueue不应该按请求创建,因为它管理内部状态,帮助你更快地提出请求(缓存),你也可以在电话轮换等事件中取消请求,你的意志就会被破坏,在这种情况下,只需要调用取消方法在Activity / Fragment的onStop()

@Override
protected void onStop () {
    super.onStop();
    if (myAdapter.getMyAdapterRequestQueue() != null) {
        myAdapter.getMyAdapterRequestQueue().cancelAll(MyAdapter.TAG);
    }
}

取消请求后,将不会调用响应回调。

© www.soinside.com 2019 - 2024. All rights reserved.