【问题标题】:Why am I not getting an error when I enter a city name which is non-existent?为什么我输入不存在的城市名称时没有收到错误消息?
【发布时间】:2016-09-27 17:46:25
【问题描述】:

我正在尝试创建一个天气应用程序,该应用程序使用 JSON 对象从天气 API 检索输入城市名称的天气信息。 我的问题是,如果我输入一个随机的城市名称,它为什么仍然能够显示不存在的 JSON 对象的详细信息? 看来我的 try 和 catch 子句没有效果?就像从来没有错误一样。 如果您输入正确的城市名称,例如伦敦,那么它将为您提供准确的信息。但是,如果您输入一个随机城市名称,例如“fhjasfhjlas”(显然不是城市),它​​仍然会提供该特定城市的信息。它不应该给我一个错误,因为它找不到那个特定的 URL 吗?当具有该名称的那些属性不存在时,显示的信息是从哪里来的。

这是我的 MainActivity.java 文件:

public class MainActivity extends AppCompatActivity {

RelativeLayout weatherLayout;
RelativeLayout beginLayout;

EditText cityName;
DownloadTask task;
TextView temperatureTV;
TextView descriptionTV;
TextView cityTV;
TextView maxtempTV;
TextView mintempTV;
TextView pressureTV;
TextView windTV;
TextView humidityTV;
TextView textView;
TextView main;
Button getWeatherButton;
ImageView weatherImage;


public void getWeather(View view)   {

    String city = cityName.getText().toString();
    cityTV.setText(city);

    try {
        String encodedCityName = URLEncoder.encode(city,"UTF-8");

        String cityURL = "http://api.openweathermap.org/data/2.5/weather?q=" + encodedCityName + "&appid=226e3e9286a8df16f6a3e4d032f58159";
        try {
            task.execute(cityURL);
        }
         catch (Exception e)   {
            Toast.makeText(getApplicationContext(), "Could not find weather, check city name and Internet connection", Toast.LENGTH_LONG).show();

        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();

        Toast.makeText(getApplicationContext(), "Could not find weather, check city name and Internet connection", Toast.LENGTH_LONG).show();
    }

    getWeatherButton.setVisibility(View.INVISIBLE);
    textView.setVisibility(View.INVISIBLE);
    cityName.setVisibility(View.INVISIBLE);

    weatherLayout.setVisibility(View.VISIBLE);

}

public class DownloadTask extends AsyncTask<String, Void , String>  {
    @Override
    protected String doInBackground(String... urls) {

        String result = "";

        URL url;

        HttpURLConnection urlConnection = null;

        try {

            url = new URL(urls[0]);

            urlConnection =(HttpURLConnection) url.openConnection();

            InputStream inputStream = urlConnection.getInputStream();

            InputStreamReader reader = new InputStreamReader(inputStream);

            int data = reader.read();

            while (data != -1)  {

                char current = (char) data;

                result += current;

                data = reader.read();

            }
            return result;

        } catch (Exception e) {

            Toast.makeText(getApplicationContext(), "Could not find weather, check city name and Internet connection", Toast.LENGTH_LONG).show();


        }

        return null;


    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        try {

            JSONObject jsonObject = new JSONObject(result);

            String weatherInfo = jsonObject.getString("weather");
            String mainInfo = jsonObject.getString("main");
            String windInfo = jsonObject.getString("wind");

            JSONArray weatherJsonArray = new JSONArray(weatherInfo);

            for (int i = 0; i < weatherJsonArray.length(); i++)    {

                JSONObject weatherJsonArrayJSONObject = weatherJsonArray.getJSONObject(i);

                main.setText(weatherJsonArrayJSONObject.getString("main"));

                descriptionTV.setText(weatherJsonArrayJSONObject.getString("description"));
            }

            JSONObject mainInfoObject = new JSONObject(mainInfo);

                Double kelvin = Double.parseDouble(mainInfoObject.getString("temp"));
                Double celcius = kelvin - 273.15;
                Double floorOfKelvin = Math.floor(celcius);
                String stringCelcius = floorOfKelvin.toString();
                temperatureTV.setText(stringCelcius + "°C");

                pressureTV.setText(mainInfoObject.getString("pressure") + "Pa");

                humidityTV.setText(mainInfoObject.getString("humidity") + " %");

                Double mintTempKelvin = Double.parseDouble(mainInfoObject.getString("temp_min"));
                Double minTempcecius = mintTempKelvin - 273.15;
                Double floorOfMinTempKelvin = Math.floor(minTempcecius);
                String stringMinTemp = floorOfMinTempKelvin.toString();

                mintempTV.setText(stringMinTemp + "°C");

                Double maxtTempKelvin = Double.parseDouble(mainInfoObject.getString("temp_max"));
                Double maxTempcecius = maxtTempKelvin - 273.15;
                Double floorOfMaxTempKelvin = Math.floor(maxTempcecius);
                String stringMaxTemp = floorOfMaxTempKelvin.toString();

                maxtempTV.setText(stringMaxTemp + "°C");




            JSONObject windInfoObject = new JSONObject(windInfo);

                windTV.setText(windInfoObject.getString("speed") + " M/h");

        } catch (JSONException e) {

           Toast.makeText(getApplicationContext(), "Could not find weather, there was am error creating the JSON Object", Toast.LENGTH_LONG).show();
        }



    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    cityName = (EditText)findViewById(R.id.cityName);

    task = new DownloadTask();

    temperatureTV = (TextView)findViewById(R.id.temperature);
    descriptionTV = (TextView)findViewById(R.id.description);
    cityTV = (TextView)findViewById(R.id.city);
    maxtempTV = (TextView)findViewById(R.id.maxtempValue);
    mintempTV = (TextView)findViewById(R.id.mintempValue);
    pressureTV = (TextView)findViewById(R.id.pressureValue);
    windTV = (TextView)findViewById(R.id.windValue);
    humidityTV = (TextView)findViewById(R.id.humidityValue);
    main = (TextView) findViewById(R.id.main);

    weatherLayout = (RelativeLayout) findViewById(R.id.weatherData);
    beginLayout = (RelativeLayout) findViewById(R.id.beginLayout);

    textView = (TextView) findViewById(R.id.textView);
    getWeatherButton = (Button) findViewById(R.id.getWeather);
}
}

这是我的 content_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.iboundiaye.jsondemo.MainActivity"
tools:showIn="@layout/activity_main"
android:background="@drawable/weathernew"
android:visibility="visible"
android:id="@+id/beginLayout">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Enter City Name"
    android:id="@+id/textView"
    android:textSize="25sp"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:textColor="#ffffff" />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/cityName"
    android:layout_below="@+id/textView"
    android:layout_centerHorizontal="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Get Weather"
    android:id="@+id/getWeather"
    android:layout_marginTop="37dp"
    android:layout_below="@+id/cityName"
    android:layout_centerHorizontal="true"
    android:onClick="getWeather" />

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:visibility="invisible"
    android:id="@+id/weatherData"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="95°"
        android:id="@+id/temperature"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="48dp"
        android:textIsSelectable="false"
        android:textSize="80sp"
        android:textColor="#ffffff" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Main"
        android:id="@+id/main"
        android:layout_below="@+id/temperature"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:textColor="#ffffff" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Description"
        android:id="@+id/description"
        android:layout_below="@+id/main"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:textColor="#ffffff" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="city"
        android:id="@+id/city"
        android:layout_below="@+id/description"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:textColor="#ffffff" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Humidity"
        android:id="@+id/humidity"
        android:layout_marginBottom="20dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:textColor="#ffffff" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Wind"
        android:id="@+id/wind"
        android:layout_alignParentStart="true"
        android:layout_above="@+id/humidity"
        android:layout_alignParentLeft="true"
        android:textColor="#ffffff" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Pressure"
        android:id="@+id/pressure"
        android:layout_alignParentStart="true"
        android:layout_above="@+id/wind"
        android:layout_alignParentLeft="true"
        android:textColor="#ffffff" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Min temp"
        android:id="@+id/mintemp"
        android:layout_alignParentStart="true"
        android:layout_above="@+id/pressure"
        android:layout_alignParentLeft="true"
        android:textColor="#ffffff" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Max temp"
        android:id="@+id/maxtemp"
        android:layout_alignParentStart="true"
        android:layout_above="@+id/mintemp"
        android:layout_alignParentLeft="true"
        android:textColor="#ffffff" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text=""
        android:id="@+id/maxtempValue"
        android:layout_toRightOf="@+id/maxtemp"
        android:layout_alignBaseline="@id/maxtemp"
        android:layout_above="@+id/mintempValue"
        android:layout_marginLeft="25dp"
        android:textColor="#ffffff" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text=""
        android:id="@+id/mintempValue"
        android:layout_toRightOf="@+id/maxtemp"
        android:layout_above="@+id/pressureValue"
        android:layout_marginLeft="25dp"
        android:textColor="#ffffff" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text=""
        android:id="@+id/pressureValue"
        android:layout_toRightOf="@+id/maxtemp"
        android:layout_above="@+id/windValue"
        android:layout_marginLeft="25dp"
        android:textColor="#ffffff" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text=""
        android:id="@+id/windValue"
        android:layout_toRightOf="@+id/maxtemp"
        android:layout_above="@+id/humidityValue"
        android:layout_marginLeft="25dp"
        android:textColor="#ffffff" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text=""
        android:id="@+id/humidityValue"
        android:layout_toRightOf="@+id/maxtemp"
        android:layout_marginLeft="25dp"
        android:layout_marginBottom="20dp"
        android:layout_alignParentBottom="true"
        android:textColor="#ffffff" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageView"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

  </RelativeLayout>
</RelativeLayout>

【问题讨论】:

  • 输入不存在城市时的值是否相同?所以也许这是 api 中的默认值...
  • 不,它不是默认输出,他们正在显示。

标签: java android json try-catch openweathermap


【解决方案1】:

在他们的 API 响应中,他们使用 cityID 编写查询以确保您获得明确的结果。

这是链接:http://openweathermap.org/current#name。使用它来获得准确的结果。

另外,看这里:http://openweathermap.org/find 当你输入一个城市名称(甚至是随机的)时,它能够找到一个城市,并且已经提到这个搜索非常灵活。因此,即使您输入一些随机文本,找到城市的机会也会更高。

【讨论】:

  • 谢谢伙计,我们似乎正在做点什么!那么您如何建议我这样做,包含不同城市 ID 的列表位于我必须下载的文件中。所以我必须在使用与以前相同的方法(在 JSON 对象中查找特定字符串)查看此文件时找到输入的城市名称的相应 id,然后使用该 id 并将其放在 URL 中?如果是这样,我如何访问包含城市名称和 ID 的下载文件?
猜你喜欢
  • 2017-01-25
  • 2013-03-28
  • 2017-10-05
  • 2017-03-13
  • 1970-01-01
  • 2014-04-12
  • 2012-09-07
  • 2016-04-24
  • 2011-04-22
相关资源
最近更新 更多