2017-07-16 104 views
0

它沒有顯示任何錯誤,但它沒有更新我在模擬器中運行它的應用程序上的正確數據。有任何想法嗎?其MainFragment深發應用其視頻講座由udacity(如果有幫助!)是由...感謝數據不在列表中顯示

public class MainActivityFragment extends Fragment { 

private ArrayAdapter<String> mForecast; 
public MainActivityFragment() { 
} 

@Override 
public void onCreate(@Nullable Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setHasOptionsMenu(true); 
} 

@Override 
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { 
    inflater.inflate(R.menu.fragment_forecast,menu); 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    int id = item.getItemId(); 
    if (id== R.id.action_refresh){ 
     FetchWeatherTask weatherTask = new FetchWeatherTask(); 
     weatherTask.execute("London"); 
     return true; 

    } 
    return super.onOptionsItemSelected(item); 
} 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    View rootView = inflater.inflate(R.layout.fragment_main, container, false); 

    String[] forecastArray = { 
      "Today - Sunny - 88/63", 
      "Tomorrow - Sunny - 88/63", 
      "Today - Sunny - 88/63", 
      "Today - Sunny - 88/63", 
      "Today - Sunny - 88/63", 
      "Today - Sunny - 88/63", 
      "Today - Sunny - 88/63" 
    }; 

    List<String> weekForecast = new ArrayList<String>(
      Arrays.asList(forecastArray)); 

    mForecast = new ArrayAdapter<String>(getActivity(),R.layout.list_item_forecast,R.id.list_item_forecast_textview,weekForecast); 

    ListView listView = (ListView)rootView.findViewById(R.id.listview_forecast); 
    listView.setAdapter(mForecast); 

    return rootView; 
} 
public class FetchWeatherTask extends AsyncTask<String,Void,String[]>{ 

    private String getReadableDateString(long time){ 
     Date date = new Date(time*1000); 
     SimpleDateFormat dateFormat = new SimpleDateFormat("E,MMM d"); 
     return dateFormat.format(date).toString(); 
    } 

    private String formatHighLows(double high, double low){ 
     long roundedHigh = Math.round(high); 
     long roundedLow = Math.round(low); 
     String highLowStr = roundedHigh+"/"+roundedLow; 
     return highLowStr; 
    } 

    private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays) throws JSONException{ 
     final String OWM_LIST = "list"; 
     final String OWM_WEATHER = "weather"; 
     final String OWM_TEMPERATURE = "temp"; 
     final String OWM_MAX = "max"; 
     final String OWM_MIN = "min"; 
     final String OWM_DATETIME = "dt"; 
     final String OWM_DESCRIPTION = "main"; 

     JSONObject forecastJSON = new JSONObject(forecastJsonStr); 
     JSONArray weatherArray = forecastJSON.getJSONArray(OWM_LIST); 

     String[] resultsStr = new String[numDays]; 
     for (int i=0;i<weatherArray.length();i++){ 

      String day,description,highAndLow; 
      JSONObject dayForecast = weatherArray.getJSONObject(i); 

      long dateTime = dayForecast.getLong(OWM_DATETIME); 
      day = getReadableDateString(dateTime); 

      JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); 
      description = weatherObject.getString(OWM_DESCRIPTION); 

      JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); 
      double high = temperatureObject.getDouble(OWM_MAX); 
      double low = temperatureObject.getDouble(OWM_MIN); 

      highAndLow = formatHighLows(high,low); 
      resultsStr[i] = day+" - "+description+" - "+ highAndLow; 
     } 
     return resultsStr; 

    } 

    @Override 
    protected String[] doInBackground(String... params) { 

     if (params.length==0){ 
      return null; 
     } 
     HttpURLConnection URLConnection = null; 
     BufferedReader reader = null; 
     String forecastJSONstring = null; 

     String format = "json"; 
     String units = "metric"; 
     int numDays = 7; 
     String app_id = "c24632b5cc62e50ba9d325cf251bad1d"; 

     try { 
      final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast?"; 
      final String QUERY_PARAM = "q"; 
      final String FORMAT_PARAM = "mode"; 
      final String UNITS_PARAM = "units"; 
      final String DAYS_PARAM = "cnt"; 
      final String APPID_PARAM = "appid"; 

      Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon() 
          .appendQueryParameter(QUERY_PARAM,params[0]) 
          .appendQueryParameter(FORMAT_PARAM,format) 
          .appendQueryParameter(UNITS_PARAM,units) 
          .appendQueryParameter(DAYS_PARAM,Integer.toString(numDays)) 
          .appendQueryParameter(APPID_PARAM,app_id).build(); 

      URL url = new URL(builtUri.toString()); 
      URLConnection = (HttpURLConnection)url.openConnection(); 
      URLConnection.setRequestMethod("GET"); 
      URLConnection.connect(); 

      InputStream inputStream = URLConnection.getInputStream(); 
      StringBuffer buffer = new StringBuffer(); 
      if (inputStream == null){ 
       return null; 
      } 
      reader =new BufferedReader(new InputStreamReader(inputStream)); 

      String line; 
      while ((line = reader.readLine())!= null){ 
       buffer.append(line+"\n"); 
      } 
      if (buffer.length()==0){ 
       return null; 
      } 
      forecastJSONstring = buffer.toString(); 

     }catch (IOException e){ 
      forecastJSONstring=null; 
      e.printStackTrace(); 
     }finally { 
      if (URLConnection!=null){ 
       URLConnection.disconnect(); 
      } 
      if (reader!=null){ 
       try { 
        reader.close(); 
       }catch (final IOException e){ 
        e.printStackTrace(); 
       } 
      } 
     } 

     try { 
      return getWeatherDataFromJson(forecastJSONstring,numDays); 

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

     return null; 
    } 

    @Override 
    protected void onPostExecute(String[] results) { 
     if (results != null){ 
     mForecast.clear(); 
      for(String i:results) { 
       mForecast.add(i); 
      } 
     } 
    } 
} 
} 

回答

0

任何時間的數據備份您的Adapter變化,你必須調用notifyDataSetChanged()(從UI線程)以查看新數據。

我沒有檢查所有的網絡/解析代碼,但我懷疑,你可以只添加這行到你的onPostExecute()方法的末尾:

mForecast.notifyDataSetChanged(); 
+0

但notifyDataSetChanged()方法內部調用時你調用add()方法,不是嗎?它的聲明。 – Rilee

+0

你是對的。我的錯。你知道'results'是否包含元素(在你的'onPostExecute()'方法中)?你可能會碰到你的'doInBackground()'方法中的許多'return null'情況。 –

+0

我再次看了幾遍。它對我來說很好看,但無法弄清楚問題出在哪裏。 – Rilee