如何从void方法传输变量?

时间:2018-05-26 17:03:24

标签: java variables methods void transfer

我需要从public void onLocationChanged(Location location)获取经度和经度并将其转移到另一个方法(JSON解析器),以便将其应用于天气API的网址。你们这个人的建议是什么?我对此很新,一个例子也会非常受欢迎。

@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);
    }

1 个答案:

答案 0 :(得分:1)

当位置已更新为作为参数给定的位置时,我猜测onLocationChanged(Location location)。所以,如果你想进一步处理它,那就从那里开始吧。

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