2016-09-27 57 views
0

我試圖創建一個天氣應用程序,它使用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> 
+0

當您輸入不存在的城市時,值是否相同?所以也許這是默認的API ... – Proxytype

+0

不,它不是默認輸出,他們正在顯示。 – prabodhprakash

回答

1

在他們的API響應,他們已致函查詢中使用cityID,以確保您得到明確的結果。

這是鏈接:http://openweathermap.org/current#name。用它來準確的結果。

此外,請參閱:http://openweathermap.org/find當您輸入城市名稱(甚至隨機)時,它能夠找到一個城市,並且已經提到此搜索非常靈活。因此,即使您隨意放置一些文字,找到城市的機會也會更高。

+0

謝謝你,我們似乎正在做點什麼! 那麼你如何建議我這樣做,包含不同城市的ID的列表就在我必須下載的文件上。 因此,我必須使用與以前相同的方法(在JSON對象中查找特定的字符串)查看此文件時輸入的城市名稱的相應ID,然後使用該ID並將其放置在URL中? 如果是這樣,我如何訪問包含城市名稱和ID的下載文件? – Ibou92

相關問題