Android天气预报源码
时间: 2023-08-12 21:08:03 浏览: 168
很抱歉,我之前的回复有误。以下是一个简单的Android天气预报app的源码示例,仅供参考:
```
public class MainActivity extends AppCompatActivity {
private TextView tvLocation, tvCondition, tvTemperature;
private ImageView ivWeatherIcon;
private ProgressBar progressBar;
private String location = "Beijing"; // 默认查询北京天气
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvLocation = findViewById(R.id.tv_location);
tvCondition = findViewById(R.id.tv_condition);
tvTemperature = findViewById(R.id.tv_temperature);
ivWeatherIcon = findViewById(R.id.iv_weather_icon);
progressBar = findViewById(R.id.progress_bar);
getWeatherData(location);
}
private void getWeatherData(String location) {
progressBar.setVisibility(View.VISIBLE);
String url = "http://api.openweathermap.org/data/2.5/weather?q=" + location + "&appid={your_app_id}&units=metric";
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONObject mainObject = response.getJSONObject("main");
JSONArray weatherArray = response.getJSONArray("weather");
JSONObject weatherObject = weatherArray.getJSONObject(0);
String condition = weatherObject.getString("description");
String iconCode = weatherObject.getString("icon");
String temperature = String.valueOf(mainObject.getDouble("temp"));
tvLocation.setText(location);
tvCondition.setText(condition);
tvTemperature.setText(temperature + "°C");
Picasso.get().load("http://openweathermap.org/img/w/" + iconCode + ".png").into(ivWeatherIcon);
progressBar.setVisibility(View.GONE);
} catch (JSONException e) {
e.printStackTrace();
progressBar.setVisibility(View.GONE);
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
progressBar.setVisibility(View.GONE);
}
});
requestQueue.add(jsonObjectRequest);
}
}
```
注意:该示例中的API Key需要替换为自己的OpenWeatherMap API Key。同时,该示例只是一个简单的实现,实际的天气预报app需要考虑更多的因素,如定位、城市搜索、天气图表等。