2017-03-18 57 views
1

我一直致力于制作一个简单的天气应用程序,显示温度,天气和位置的描述。我能够得到位置,但无法弄清楚如何从OpenWeatherMap获取天气的描述,并且它现在已经让我烦恼了几个小时。这是代码的一部分,我有这样的信息:不知道如何从OpenWeatherMap api获取描述,只有地点和温度

@Override 
protected void onPostExecute(String result){ 
    super.onPostExecute(result); 
    try { 
     JSONObject jsonObject = new JSONObject(result); 
     JSONObject weatherDatas = new JSONObject(jsonObject.getString("main")); 



     double temperature = Double.parseDouble(weatherDatas.getString("temp")); 

     int tempIn = (int) (temperature*1.8-459.67); 

     String placeName = (String) jsonObject.get("name"); 


     MainActivity.tempeartureTextView.setText("" + tempIn); 
     MainActivity.placeTextView.setText(placeName); 
     Log.i("it made it", "to end of DownloadTask"); 
     //using http://samples.openweathermap.org/data/2.5/weather?zip=94040,us&appid=b1b15e88fa797225412429c1c50c122a1 with zip code 

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

} 

但是对于我的生活,我无法弄清楚如何获得描述。

代码的其余部分都在这里:MainActivity:http://pastebin.com/e2NtTSiP

DownloadTask:http://pastebin.com/ScEREz52

我跟着这个YouTube的教程,所以我不太明白一切,但我还挺想就去做了并重新开始,直到我能把它弄清楚为止。

回答

0

如果您的JSON响应以下:

{ 
    "coord": { 
    "lon": -122.08, 
    "lat": 37.39 
    }, 
    "weather": [ 
    { 
     "id": 500, 
     "main": "Rain", 
     "description": "light rain", 
     "icon": "10n" 
    } 
    ], 
    "base": "stations", 
    "main": { 
    "temp": 277.14, 
    "pressure": 1025, 
    "humidity": 86, 
    "temp_min": 275.15, 
    "temp_max": 279.15 
    }, 
    "visibility": 16093, 
    "wind": { 
    "speed": 1.67, 
    "deg": 53.0005 
    }, 
    "clouds": { 
    "all": 1 
    }, 
    "dt": 1485788160, 
    "sys": { 
    "type": 1, 
    "id": 471, 
    "message": 0.0116, 
    "country": "US", 
    "sunrise": 1485789140, 
    "sunset": 1485826300 
    }, 
    "id": 5375480, 
    "name": "Mountain View", 
    "cod": 200 
} 

为了得到从响应天气描述,

  1. 得到 “天气” 阵列
  2. 每个JSON本内天气对象数组,获取JSON对象的“description”属性

    JSONObject obj = new JSONObject(response); 
    JSONArray arr = obj.getJSONArray("weather"); 
    for (int i = 0; i < arr.length(); i++) { 
            JSONObject each = arr.get(i); 
            each.getString("description"); 
    } 
    
+0

每当我添加它时,它只显示我放入文本视图的默认值。另外,我得到这个错误:https://gyazo.com/819739a0b7f46702ce3ac20639e49959当我选择顶部选项时,它将其更改为:JSONObject each =(JSONObject)arr.get(i); –

+0

修复了代码。你必须从响应字符串中新建json对象。 –

0
 String weatherInfo = jsonObject.getString("weather"); 

     Log.i("Weather content", weatherInfo); 

     JSONArray arr = new JSONArray(weatherInfo); 

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

      JSONObject jsonPart = arr.getJSONObject(i); 

      String main = ""; 
      String description = ""; 

      main = jsonPart.getString("main"); 
      description = jsonPart.getString("description"); 

      MainActivity.descriptionTextView.setText(description); 

     } 

这给我修好了!