2015-09-03 86 views
0

我在doInBackground方法的Asynctask類中的值'return'中遇到問題。我得到一個錯誤,關於'在下面的代碼中缺少return語句。Android Asynctask返回問題

'公共類ForecastNetwork擴展的AsyncTask {

public final String TAG = ForecastNetwork.class.getSimpleName(); 

    @Override 
    protected Void doInBackground(Void... params) { 

     HttpURLConnection urlConnection = null; 
     BufferedReader reader = null; 

//將包含原始JSON響應作爲一個字符串。 String forecastJsonStr = null;

 try { 
      // Construct the URL for the OpenWeatherMap query 
      // Possible parameters are avaiable at OWM's forecast API page, at 
      // http://openweathermap.org/API#forecast 
      URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7"); 

      // Create the request to OpenWeatherMap, and open the connection 
      urlConnection = (HttpURLConnection) url.openConnection(); 
      urlConnection.setRequestMethod("GET"); 
      urlConnection.connect(); 

      // Read the input stream into a String 
      InputStream inputStream = urlConnection.getInputStream(); 
      StringBuffer buffer = new StringBuffer(); 
      if (inputStream == null) { 
       // Nothing to do. 
       return null; 
      } 
      reader = new BufferedReader(new InputStreamReader(inputStream)); 

      String line; 
      while ((line = reader.readLine()) != null) { 
       // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) 
       // But it does make debugging a *lot* easier if you print out the completed 
       // buffer for debugging. 
       buffer.append(line + "\n"); 
      } 

      if (buffer.length() == 0) { 
       // Stream was empty. No point in parsing. 
       return null; 
      } 
      forecastJsonStr = buffer.toString(); 
     } catch (IOException e) { 
      Log.e(TAG, "Error ", e); 
      // If the code didn't successfully get the weather data, there's no point in attemping 
      // to parse it. 
      return null; 
     } finally { 
      if (urlConnection != null) { 
       urlConnection.disconnect(); 
      } 
      if (reader != null) { 
       try { 
        reader.close(); 
       } catch (final IOException e) { 
        Log.e(TAG, "Error closing stream", e); 
       } 
      } 
     } 


    }` 

我最後應該返回什麼?

回答

0

我以爲你忘了處理結果返回

forecastJsonStr = buffer.toString(); 
    return forecastJsonStr; 
+0

我必須在最後寫?實際上,我正在通過udacity舉辦的Google開發者開展在線課程,他們沒有做過任何類似的事情。 – Rebecca

+0

是否重要,如果我改變爲結果參數,即公共類ForecastTask擴展公共類ForecastTask擴展?幫我。我真的很黑。 – Rebecca

+0

謝謝。其實它按照你的說法工作。:) – Rebecca