当我输入一个不存在的城市名称时,为什么我没有收到错误?

时间:2016-09-27 17:46:25

标签: java android json try-catch openweathermap

我正在尝试创建一个天气应用程序,该应用程序使用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>

1 个答案:

答案 0 :(得分:1)

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

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

此外,请参阅此处:http://openweathermap.org/find当您输入城市名称(甚至是随机的)时,它可以找到一个城市,并且已经提到此搜索非常灵活。因此,即使您放置了一些随机文本,找到城市的机会也会更高。