2017-03-02 164 views
0

以下是通過輸入城市名或地名查找天氣的代碼..結果是從doInBackground方法串......但不幸的是它的返回空...JSON結果返回null

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

     if(result == null){ 
      Toast.makeText(MainActivity.this,"Place not found",Toast.LENGTH_LONG).show(); 
     } 
     else{ 
      try { 

       String message = ""; 

       JSONObject jsonObject = new JSONObject(result); 

       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"); 

        if (main != "" && description != "") { 

         message += main + ": " + description + "\r\n"; 

        } 

       } 

       if (message != "") { 

        weatherReport.setText(message); 

       } else { 

        Toast.makeText(getApplicationContext(), "Could not find weather", Toast.LENGTH_LONG).show(); 

       } 


      } catch (JSONException e) { 

       Toast.makeText(getApplicationContext(), "Could not find weather", Toast.LENGTH_LONG).show(); 

      } 

的doInBackground()方法..

protected String doInBackground(String... urls) { 

     String result = ""; 
     URL url; 
     HttpURLConnection httpURLConnection; 

     try { 
      url = new URL(urls[0]); 
      httpURLConnection = (HttpURLConnection) url.openConnection(); 
      InputStream in = httpURLConnection.getInputStream(); 
      InputStreamReader reader = new InputStreamReader(in); 
      int data = reader.read(); 
      while(data != -1){ 
       char current = (char) data; 
       result += current; 

       data = reader.read(); 
      } 
      return result; 

     } 
     //combined the exceptions MalformedURL and IOException to a common to display a toast msg 
     catch (Exception e) { 
      e.printStackTrace(); 
     } 

     return null; 

    } 

下載網址..DownloadTask是從的AsyncTask <擴展的類的名稱>並具有方法doInBackground和onPostExecute()..請幫助我,爲什麼結果字符串返回空。

weather.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 

      try { 

       //to hide the keyboard after pressing the button 
       InputMethodManager manager = 
         (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
       manager.hideSoftInputFromInputMethod(weatherInput.getWindowToken(),0); 

       DownloadTask downloadTask = new DownloadTask(); 

       //used to encode the entered input for url.. for example San Fransisco appears in url 
       //as San%20Fransisco ... and to enable that we use the encoder... 
       String encodedCity = URLEncoder.encode(city,"UTF-8"); 

       downloadTask.execute("http://api.openweathermap.org/data/2.5/weather?q=" + encodedCity + 
         "&appid=cd66504ca815ddc1971662a9f2147f84\n"); 

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

     } 
    }); 
+0

你檢查從界面的「消息」的迴應:「無效的API key請http://openweathermap.org/faq#error401獲取更多信息。」 – zombie

+0

那麼......你做了'返回null;',**和**你打印一個異常,所以也許檢查logcat –

+0

另外,'main!=「」'是**不是** [如何比較字符串Java](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) –

回答

0

我發現你的代碼的幾個問題。嘗試這個。

String message = ""; 
JSONObject jsonObject = new JSONObject(result); 
JSONArray arr = jsonObject.optJSONArray("weather"); 
for (int i = 0; i < arr.length(); i++) { 
    JSONObject jsonPart = arr.optJSONObject(i); 
    String main = jsonPart.optString("main"); 
    String description = jsonPart.optString("description"); 
    if (!TextUtils.isEmpty(main) && !TextUtils.isEmpty(description)) { 
     message += main + ": " + description + "\r\n"; 
    } 
} 
if (!TextUtils.isEmpty(message)) { 
     weatherReport.setText(message); 
    } else { 
     Toast.makeText(getApplicationContext(), "Could not find weather", Toast.LENGTH_LONG).show(); 
    } 
+0

我更改了代碼,仍然收到了與顯示敬酒的相同錯誤消息顯示「找不到地方」 ..pls解釋 –

+0

似乎你得到一些例外 - 那是什麼? 1.在您的Android清單文件中添加一個INTERNET_PERMISSION 2.檢查異常並解決它。 3.我認爲,閱讀流代碼可能不完美。 – albeee

+0

所以用這個。 InputStreamReader reader = new InputStreamReader(in); BufferedReader buffReader = new BufferedReader(reader); String readLine; StringBuffer stringBuffer = new StringBuffer();當((readLine = buffReader.readLine())!= null){ stringBuffer.append(readLine).append(「\ n」); } \t \t \t result = sb.toString(); reader.close(); in.close(); – albeee

0

請在您編寫任何Java代碼之前測試您的API 之前


您的網址中有一個尾隨\n

在你的代碼只需打開實際的URL,或捲曲它...

curl 'http://api.openweathermap.org/data/2.5/weather?q=San%20Antonio&appid=cd66504ca815ddc1971662a9f2147f84\n' | jq 

{ 
    "cod": 401, 
    "message": "Invalid API key. Please see http://openweathermap.org/faq#error401 for more info." 
} 

末取下\n

{ 
    "coord": { 
    "lon": -98.49, 
    "lat": 29.42 
    }, 
    "weather": [ 
    { 
     "id": 800, 
     "main": "Clear", 
     "description": "clear sky", 
     "icon": "01n" 
    } 
    ], 
    "base": "stations", 
    "main": { 
    "temp": 288.15, 
    "pressure": 1023, 
    "humidity": 27, 
    "temp_min": 285.15, 
    "temp_max": 291.15 
    }, 
    "visibility": 16093, 
    "wind": { 
    "speed": 3.6, 
    "deg": 30 
    }, 
    "clouds": { 
    "all": 1 
    }, 
    "dt": 1488423180, 
    "sys": { 
    "type": 1, 
    "id": 2713, 
    "message": 0.0075, 
    "country": "US", 
    "sunrise": 1488459476, 
    "sunset": 1488501264 
    }, 
    "id": 4726206, 
    "name": "San Antonio", 
    "cod": 200 
} 
+0

我在最後刪除了\ n,但仍然得到了與它顯示相同的錯誤敬酒的地方沒有發現..說明解釋 –

+0

你的解析仍然可以拋出異常。請嘗試使用Volley https://developer.android.com/training/volley/request.html#request-json –