java - 如何从 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);
}
解决方案
我猜onLocationChanged(Location location)
当位置更新为作为参数给出的位置时调用。所以,如果你想进一步处理它,就从那里拿走它。
public void onLocationChanged(Location loc) {
String jsonLoc = createJson(loc);
sendToWeatherApi(jsonLoc);
}
推荐阅读
- tcl - Tcl:替换特定列中的字符串
- vb.net - VB.Net / HttpWebRequest 内存泄漏
- java - 试图将开放处理代码转换成 pj.5s
- python - 求给定数 N 的偶数完全平方因数
- f# - F# 中带有 Seq.unfold 的 Seq.cache
- javascript - jQuery中的可拖动滑块标尺
- python - Tabula 未检测到某些带有使用相同软件构建的 pdf 的表格
- visual-studio-code - 如何从 ESLint 错误中删除红色背景?
- firebase - Cloud Functions 中的 puppeteer.launch 抛出错误
- python - Django:assertEquals 与 QuerySet 具有视觉上相等的结果