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

标签 android retrofit2 weather-api

我正在创建天气应用程序,让用户可以选择按任何城市搜索天气。当用户输入有效的城市名称时,我的应用程序工作正常,但当用户输入无效的字符串 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/

相关文章:

java - ScheduledThreadPoolExecutor afterExecute的runnable.toString不一样

android - 创建自定义 View 作为可跨项目使用的模块化和可重用组件

java - 线圈图像加载器 : Cache Bitmap with a key

android - 照片未出现在 RecyclerView 中

android - 使用 Retrofit 调用 api

android - 请求码==400,尝试登录webservice

java - Android lib Admob 没有足够的空间来显示平板电脑广告

javascript - 网站使用 yahoo api 根据当前天气显示 css 动画

javascript - 跨源请求被阻止 : Multiple API; need to aggregate data

weather-api - 从 Web API 数据创建雷达图像