天气预报安卓APP代码
时间: 2023-11-01 19:08:29 浏览: 51
抱歉,我作为一个语言模型,无法提供完整的代码。但是,以下是一个简单的天气预报应用程序的代码示例,使用了第三方API OpenWeatherMap:
```java
public class WeatherActivity extends AppCompatActivity {
private TextView tvTemperature, tvCity, tvDescription;
private ImageView ivIcon;
private String API_KEY = "your_api_key";
private String API_URL = "http://api.openweathermap.org/data/2.5/weather?q=%s&units=metric&APPID=%s";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weather);
tvTemperature = findViewById(R.id.tv_temperature);
tvCity = findViewById(R.id.tv_city);
tvDescription = findViewById(R.id.tv_description);
ivIcon = findViewById(R.id.iv_icon);
String cityName = getIntent().getStringExtra("city_name");
String url = String.format(API_URL, cityName, API_KEY);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONObject main = response.getJSONObject("main");
JSONArray weatherArray = response.getJSONArray("weather");
JSONObject weather = weatherArray.getJSONObject(0);
double temperature = main.getDouble("temp");
String description = weather.getString("description");
String icon = weather.getString("icon");
tvTemperature.setText(String.format("%.0f°C", temperature));
tvDescription.setText(description);
tvCity.setText(cityName);
Glide.with(WeatherActivity.this)
.load("http://openweathermap.org/img/w/" + icon + ".png")
.into(ivIcon);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(WeatherActivity.this, "Error: " + error, Toast.LENGTH_LONG).show();
}
});
Volley.newRequestQueue(this).add(jsonObjectRequest);
}
}
```
需要注意的是,这个示例应用程序使用了第三方库 Glide 和 Volley。在您的项目中使用前,请确保已将其添加到您的项目中。此外,您需要在 OpenWeatherMap 网站上注册并获取 API 密钥,然后将其替换为上面代码中的 `your_api_key`。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)