数据未在Listview中显示

时间:2017-07-16 14:43:48

标签: android json listview openweathermap

它没有显示任何错误,但它没有更新我在模拟器中运行它的应用程序上的正确数据。有任何想法吗?它是 SunShine App 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);
            }
        }
    }
}
}

1 个答案:

答案 0 :(得分:0)

每次支持Adapter更改的数据都必须调用notifyDataSetChanged()(来自UI线程)才能查看新数据。

我没有检查过你的所有网络/解析代码,但我怀疑你可以将这一行添加到onPostExecute()方法的末尾:

mForecast.notifyDataSetChanged();