I'm trying to alter the below code so that it will change the city and the measurement units (i.e. Fahrenheit and Celsius) in the below code. I want the user to be able to type a city name into an EditText field, hit a button, and it will change the weather location to that city. I also want a preferance to be set to display temperature in either Celsius or Fahrenheit. I'm not sure how to do that though. Below is my current code. The String url is the API I need to be changed based on the input.
Does anyone have any Ideas?
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);
}
Say, you have two EditText
, one having the city name, has id set to etCity
.
Another one has id set to etMetric
, having the unit of choice.
If etMetric
has value set to imperial
, then the imperial unit will be used, otherwise metric unit.
Now you have a button, for sending request. When the button is clicked, this below function will be called:
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
}