2017-05-08 54 views
0

我使用我想從API獲取特定天氣一部分,我下面的代碼,所以我使用JSON我無法JSObject轉換API密鑰


這裏下面鏈接的https://openweathermap.org/current
的API在這裏我想天氣部分類型的
http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b1b15e88fa797225412429c1c50c122a1

值null org.json.JSONObject $ 1位API密鑰無法被轉換爲JSONObject的


我使用的AsyncTask

我的MainActivity在這裏

公共類MainActivity擴展AppCompatActivity {

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

    DownloadWeatherData downloadWeatherData = new DownloadWeatherData(); 

    try { 

     downloadWeatherData.execute("http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b1b15e88fa797225412429c1c50c122a1").get(); 


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

}

這是我的java文件

公共類DownloadWeatherData擴展AsyncTask {

String weatherdata; 
@Override 
protected String doInBackground(String... urls) 
{ 
    try { 
     URL url = new URL(urls[0]); 

     HttpURLConnection connection =(HttpURLConnection) url.openConnection(); 
     connection.connect(); 

     InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream()); 

     int data = inputStreamReader.read(); 

     while(data!=-1) 
     { 
      char str = (char)data; 
      weatherdata+=str; 

      data = inputStreamReader.read(); 
     } 

     return weatherdata; 

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

    } catch (IOException e) { 

     e.printStackTrace(); 
    } 
    return null; 
} 

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


    try { 
     JSONObject jsonObject = new JSONObject(s); 
     String info = jsonObject.getString("weather"); 
     Log.d("weatherpart",info); 

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

    } 
} 

}

+0

我認爲改造是HttpURLConnection的替代 –

回答

0

你做錯了。 天氣是一個數組而不是json對象。像這樣做:

JSONObject jsonObj = new JSONObject(s); 

JSONArray ja_data = jsonObj.getJSONArray("weather"); 
int length = ja_data.length(); 
for(int i=0; i<length; i++) { 
    JSONObject jsonObj = ja_data.getJSONObject(i); 
    . 
    . 
    . 
} 
+0

我不得不刪除try和catch塊甚至還有同樣的錯誤如上顯示 –