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

时间:2018-05-04 06:41:23

标签: 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"
}

Result.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;
    }
}

2 个答案:

答案 0 :(得分:2)

您的应用终止,因为它正在寻找因名称错误而不存在的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,现在我不能继续寻找,但是你需要做的就是检查你的回答的“鳕鱼”是否与404不同解析json

答案 1 :(得分:1)

请使用此

public void onResponse(Call<Result> call, Response<Result> response){
try {
    cityName.setText(response.body().getCityName() + "," + 
    response.body().getSys().getCounty());
        String temperature = String.format("%.2f", 
    response.body().getMain().getTemp()) + "°C";
        temp.setText(temperature);
} catch(Exception e {               
    e.printStackTrace();
}