首页 > 解决方案 > 如何从 void 方法传输变量?

问题描述

我需要从中获取纬度和经度:public void onLocationChanged(Location location)并将其传输到另一个方法(JSON 解析器),以便可以将其应用于天气 API 的 url。你们对此有何建议?我对此很陌生,一个例子也将不胜感激。

@Override
public void onLocationChanged(Location location) {
    url = "https://api.openweathermap.org/data/2.5/weather?lat=" + location.getLatitude() + "&lon=" + location.getLongitude() + "&appid=5d8fea5f1c9cdfe8af473504e5f9002a";
    Log.i("api", url);

    //double lat = location.getLatitude();
   // double lng = location.getLongitude();

}

@Override
public void onStatusChanged(String s, int i, Bundle bundle) {

}

@Override
public void onProviderEnabled(String s) {

}

@Override
public void onProviderDisabled(String s) {

}  

我需要的是从 Location 方法到 JsonObjectRequest 的 URL

private void jsonParse() {


        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {

                    JSONObject weatherData = response.getJSONObject("main");
                    double temp = weatherData.getDouble("temp");
                    double tempHigh = weatherData.getDouble("temp_max");
                    double tempLow = weatherData.getDouble("temp_min");
                    double humidity = weatherData.getDouble("humidity");


                    Log.i("JSONWork", String.valueOf(weatherData));
                    TV_temp_max.append("Highest Temperature: " + tempHigh);
                    TV_temp_min.append("Lowest Temperature: " + tempLow);
                    TV_temp.append("Current Temperature: " + temp);
                    TV_humidity.append("Humidity: %" + humidity);

                    JSONObject locationData = response.getJSONObject("sys");
                    String country = locationData.getString("country");
                    String city = locationData.getString("name");
                    TV_country.append(country);
                    TV_city.append(city);

                } catch (JSONException e) {
                    Log.i("error", "JSON is not working");
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();


            }
        });

        mQueue.add(request);
    }

标签: javavariablesmethodsvoidtransfer

解决方案


我猜onLocationChanged(Location location)当位置更新为作为参数给出的位置时调用。所以,如果你想进一步处理它,就从那里拿走它。

public void onLocationChanged(Location loc) {
    String jsonLoc = createJson(loc);
    sendToWeatherApi(jsonLoc);
}

推荐阅读