gpt4 book ai didi

android - 改造-处理搜索选项中的无效数据

转载 作者:行者123 更新时间:2023-11-29 16:42:01 27 4
gpt4 key购买 nike

我正在创建天气应用程序,让用户可以选择按任何城市搜索天气。当用户输入有效的城市名称时,我的应用程序工作正常,但当用户输入无效的字符串 ex: asndfs,bdfbsj 然后我的应用程序终止。

如何处理?这样我的应用就不会终止而是给用户消息说请输入有效的城市名称

这是我在用户输入字符串时调用 openWeatherApi 时的代码。

private void getWeatherDataByCity(String city) {
params = new HashMap<>();
params.put(Constants.CITY, city);
params.put(Constants.UNIT, Constants.UNITS);
params.put(Constants.APP_ID, Constants.API_KEY);
RetrofitClient.getData(params).enqueue(new Callback<Result>() {
@Override
public void onResponse(Call<Result> call, Response<Result> response) {
cityName.setText(response.body().getCityName() + "," + response.body().getSys().getCounty());
String temperature = String.format("%.2f", response.body().getMain().getTemp()) + "°C";
temp.setText(temperature);

}

@Override
public void onFailure(Call<Result> call, Throwable t) {
}
});
}

用户输入有效城市时的 Json 响应:

{
"coord": {
"lon": 77.22,
"lat": 28.65
},
"weather": [
{
"id": 721,
"main": "Haze",
"description": "haze",
"icon": "50d"
}
],
"base": "stations",
"main": {
"temp": 305.15,
"pressure": 1008,
"humidity": 43,
"temp_min": 305.15,
"temp_max": 305.15
},
"visibility": 3000,
"wind": {
"speed": 5.7,
"deg": 110
},
"clouds": {
"all": 20
},
"dt": 1525413600,
"sys": {
"type": 1,
"id": 7809,
"message": 0.0996,
"country": "IN",
"sunrise": 1525392476,
"sunset": 1525440495
},
"id": 1273294,
"name": "Delhi",
"cod": 200
}

用户输入无效城市时的Json响应:

{
"cod": "404",
"message": "city not found"
}

结果.java

public class Result {
@SerializedName("main")
private Temprature main;
@SerializedName("sys")
private Sys sys;
@SerializedName("cod")
private int cod;
@SerializedName("message")
private String message;
@SerializedName("name")
private String cityName;
@SerializedName("weather")
private List<Weather> weather = new ArrayList<>();

public List<Weather> getWeather() {
return weather;
}

public Temprature getMain() {
return main;
}

public Sys getSys() {
return sys;
}

public String getCityName() {
return cityName;
}

public int getCod() {
return cod;
}

public String getMessage() {
return message;
}
}

最佳答案

您的应用程序终止,因为它正在寻找一个由于名称错误而不存在的 json 字段。试试这个:

 public void onResponse(Call<Result> call, Response<Result> response) {
if (response.code() == 404) {
Toast.makeText(MainActivity.this, response.message(), Toast.LENGTH_SHORT).show();
cityName.setText(response.message());
temp.setText("0" + "°C");
} else {
cityName.setText(response.body().getCityName() + "," +
response.body().getSys().getCounty());
String temperature = String.format("%.2f", response.body().getMain().getTemp()) + "°C";
temp.setText(temperature);
}
}

编辑:我不知道如何从结果类型的响应中获取 json,现在我不能继续寻找,但您需要做的就是在尝试之前检查您的响应的“cod”是否与 404 不同解析json

关于android - 改造-处理搜索选项中的无效数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50168731/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com