如何判断是否该城是OpenWeatherMap API和Android中不正确 [英] How to tell the if the City is incorrect in OpenWeatherMap api and in android

查看:1027
本文介绍了如何判断是否该城是OpenWeatherMap API和Android中不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个应用程序,它会告诉使用OpenWeatherMap.org API一个城市的天气情况。在这个程序,我让用户写一个城市名称和数据会从网上获取。但是,如果用户输入错误的城市。

I am creating an app which will tell the weather condition of a city using the OpenWeatherMap.org api. In this app I let user to write a city name and the data will be fetched from the web. But what if the user entered wrong city.

例如,如果用户输入LOMDON,而不是伦敦。

For example if a user entered Lomdon instead of London.

我应该在这种情况下做的。我使用的API
http://api.openweathermap.org/data/2.5/weather?q= +城市名

What should I do in that case. The Api I am using is "http://api.openweathermap.org/data/2.5/weather?q="+city name

在此先感谢您的帮助,我是新的android开发。

Thanks in advance for the help, I am new to android development.

推荐答案

如果城市是不正确的API返回的错误信息。你可以检查它是这样的:

If the city is incorrect your API returns an error message. You can check it like this:

http://api.openweathermap.org/data/2.5/weather q = LOMDON

    try {
        String msg = jsonObject.getString("message");
        if (msg.equalsIgnoreCase("Error: Not found city")) {
            Log.e("TAG", "City not found");
        } else {
            // Use the data
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

我没有使用的原因 COD 它看起来像返回code,是如果这个城市中找到 COD 是一个int,如果它没有发现它是一个字符串。一种误导设计JSON这样的。

The reason I didn't use cod which looks like the return code, is that if the city is found cod is an int and if it's not found it's a string. Kind of misleading to design the JSON like that.

这篇关于如何判断是否该城是OpenWeatherMap API和Android中不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆