我正在尝试更改以下代码,以便它将更改以下代码中的城市和度量单位(即华氏和摄氏)。我希望用户能够在EditText字段中输入城市名称,单击按钮,它将天气位置更改为该城市。我还希望将显示温度设置为摄氏度或华氏度。我不知道该怎么做。下面是我当前的代码。字符串url是需要根据输入更改的API。
有人有任何想法吗?
String url = "http://api.openweathermap.org/data/2.5/weather?q=Indianapolis&units=imperial&appid=OpenWeatherMapAPIKey";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject responseObject) {
//tempTextView.setText("Response: " + response.toString());
Log.v("Weather", "Response: " + responseObject.toString());
try {
JSONObject mainJSONObject = `enter code here`responseObject.getJSONObject("main");
JSONArray weatherArray = responseObject.getJSONArray("weather");
JSONObject firstWeatherObject = weatherArray.getJSONObject(0);
String temp = Integer.toString((int) Math.round(mainJSONObject.getDouble("temp")));
String weatherDescription = firstWeatherObject.getString("description");
String city = responseObject.getString("name");
tempTextView.setText(temp);
weatherDescTextView.setText(weatherDescription);
cityTextView.setText(city);
int iconResourceId = getResources().getIdentifier("icon_" + weatherDescription.replace(" ", ""), "drawable", getPackageName());
weatherImageView.setImageResource(iconResourceId);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
});
// Access the RequestQueue through your singleton class.
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(jsonObjectRequest);
}
答案 0 :(得分:0)
说,您有两个EditText
,一个具有城市名称,其ID设置为etCity
。
另一个ID设置为etMetric
,具有选择的单位。
如果etMetric
的值设置为imperial
,则将使用英制单位,否则使用 metric 单位。
现在您有一个按钮,用于发送请求。单击该按钮时,以下功能将被调用:
private void weatherRequest(){
EditText etCity,etMetric;
etCity= findViewById(R.id.etCity);
etMetric= findViewById(R.id.etMetric);
String city= etCity.getText().toString();
String unit= etCity.getText().toString();
if(!unit.equals("imperial"))
unit="metric";
String url = "http://api.openweathermap.org/data/2.5/weather?q="+etCity+"&units="+etMetric+"&appid=OpenWeatherMapAPIKey";
//now request the server with this url
}