Android实现简单天气查询
时间: 2023-08-05 21:50:34 浏览: 62
要实现简单的天气查询,可以借助第三方天气 API 来获取天气信息。以下是一个简单的 Android 天气查询应用的实现步骤:
1. 在布局文件中添加一个输入框和一个按钮,用于用户输入城市名称和触发查询操作。
2. 在 Activity 中获取输入框和按钮的实例,并且设置按钮的点击事件监听器。
3. 在按钮的点击事件监听器中,获取用户输入的城市名称,并且使用第三方天气 API 发送 HTTP 请求获取天气信息。
4. 解析请求返回的 JSON 数据,获取需要的天气信息。
5. 将获取到的天气信息更新到应用界面中,例如更新一个文本框显示查询结果。
以下是一个使用和风天气 API 实现的简单天气查询应用的示例代码:
1. 添加依赖库
在 build.gradle 文件中添加以下依赖库:
```
implementation 'com.squareup.okhttp3:okhttp:3.11.0'
implementation 'com.google.code.gson:gson:2.8.5'
```
2. 编写布局文件
在 activity_main.xml 文件中添加以下代码:
```xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/city_edit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:hint="请输入城市名称" />
<Button
android:id="@+id/search_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/city_edit"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:text="查询" />
<TextView
android:id="@+id/result_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/search_btn"
android:layout_margin="16dp"
android:text="查询结果将显示在这里"
android:textSize="20sp" />
</RelativeLayout>
```
3. 编写 Activity 代码
在 MainActivity.java 文件中添加以下代码:
```java
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.google.gson.Gson;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private EditText mCityEdit;
private Button mSearchBtn;
private TextView mResultText;
// 和风天气 API 的 API Key
private static final String API_KEY = "your_api_key_here";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCityEdit = (EditText) findViewById(R.id.city_edit);
mSearchBtn = (Button) findViewById(R.id.search_btn);
mResultText = (TextView) findViewById(R.id.result_text);
mSearchBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String city = mCityEdit.getText().toString();
if (!TextUtils.isEmpty(city)) {
// 发送 HTTP 请求获取天气信息
requestWeather(city);
}
}
});
}
// 发送 HTTP 请求获取天气信息
private void requestWeather(String city) {
String url = "https://free-api.heweather.net/s6/weather/now?key=" + API_KEY + "&location=" + city;
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
e.printStackTrace();
showResult("查询失败:" + e.getMessage());
}
@Override
public void onResponse(Response response) throws IOException {
if (response.isSuccessful()) {
String responseStr = response.body().string();
WeatherResponse weatherResponse = new Gson().fromJson(responseStr, WeatherResponse.class);
if (weatherResponse != null && "ok".equals(weatherResponse.getHeWeather6().get(0).getStatus())) {
// 解析请求返回的 JSON 数据,获取需要的天气信息
final String weatherInfo = weatherResponse.getHeWeather6().get(0).getNow().getCond_txt() + "," + weatherResponse.getHeWeather6().get(0).getNow().getTmp() + "℃";
// 将获取到的天气信息更新到应用界面中
runOnUiThread(new Runnable() {
@Override
public void run() {
showResult("查询结果:" + weatherInfo);
}
});
} else {
showResult("查询失败:" + weatherResponse.getHeWeather6().get(0).getStatus());
}
} else {
showResult("查询失败:" + response.message());
}
}
});
}
// 将查询结果更新到应用界面中
private void showResult(final String result) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mResultText.setText(result);
}
});
}
// 天气信息的 JSON 数据模型类
private static class WeatherResponse {
private HeWeather6Bean heWeather6;
public HeWeather6Bean getHeWeather6() {
return heWeather6;
}
public void setHeWeather6(HeWeather6Bean heWeather6) {
this.heWeather6 = heWeather6;
}
public static class HeWeather6Bean {
private String status;
private NowBean now;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public NowBean getNow() {
return now;
}
public void setNow(NowBean now) {
this.now = now;
}
public static class NowBean {
private String cond_txt;
private String tmp;
public String getCond_txt() {
return cond_txt;
}
public void setCond_txt(String cond_txt) {
this.cond_txt = cond_txt;
}
public String getTmp() {
return tmp;
}
public void setTmp(String tmp) {
this.tmp = tmp;
}
}
}
}
}
```
注意:上述代码中的 `your_api_key_here` 需要替换成自己申请的和风天气 API 的 API Key。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)