-3

我正在编写构建阳光应用程序的 udacity android 教程,我创建了一个刷新按钮来更新天气信息。单击时它没有更新任何信息,我只是得到一个 JSONException。这是代码:_

对于预测片段:

package com.example.android.sunshine;

import android.net.Uri;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.text.format.Time;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * A placeholder fragment containing a simple view.
 */
public class ForecastFragment extends Fragment {

    private ArrayAdapter<String> mForecastAdapter;

    public ForecastFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Add this line in order for this to handle menu events.
        setHasOptionsMenu(true);
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The actionbar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml
        int id = item.getItemId();
        if (id == R.id.action_refresh) {
            FetchWeatherTask weatherTask = new FetchWeatherTask();
            weatherTask.execute("94043");
            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);

        //Once the root view for the fragment has been created, its time to populate
        //the ListView with some dummy data.

        //Create some dummy data for the ListView. Here's a sample  weekly forecast
        //represented as "day, whether, high/low"

        String[] forecastArray = {
                "Today - Sunny - 88/63",
                "Tomorrow - Foggy - 70/40",
                "Weds - Cloudy - 72/63",
                "Thurs - Asteroids - 75/65",
                "Fri - Heavy Rain - 65/56",
                "Sat - HELP TRAPPED IN WEATHERSTATION - 60/51",
                "Sun - Sunny - 80/68"

        };

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

        // Now that we have some dummy forecast data, create an ArrayAdapter.
        // The ArrayAdapter will take data from a source (like our dummy forecastarary)
        // and use it to populate the ListView it's attached to.

        ArrayAdapter mForecastAdapter =
                new ArrayAdapter<String>(
                        // The current context (this fragment's parent activity)
                        getActivity(),
                        // ID of list item layout
                        R.layout.list_item_forecast,
                        // ID of the textview to populate
                        R.id.list_item_forecast_textview,
                        // Forecast data
                        weekForecast);

        // Get a reference to the ListView, and attach this adapter
        ListView listView = (ListView) rootView.findViewById(
                R.id.listview_forecast);
        listView.setAdapter(mForecastAdapter);


        return rootView;

    }

    public class FetchWeatherTask extends AsyncTask<String, Void, String[]> {

        private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();

        /* The date/time conversion code is going to be moved outside the asynctask later,
        * so for convinience we are breaking it out into its own method now.
         */
        private String getReadableDateString(long time){
            // Because the API returns a unix timestamp (measured in seconds),
            // it must be converted to milliseconds in order to be converted to valid date.
            SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd");
            return  shortenedDateFormat.format(time);
        }

        /*
         * Prepare the weather high/lows for presentation
         */
        private String formatHighLows(double high, double low){
            // For presentation, assume the user dosen't care about tenths of a degree
            long roundedHigh = Math.round(high);
            long roundedLow = Math.round(low);

            String highLowStr = roundedHigh + "/" + roundedLow;
            return highLowStr;
        }

        /**
         * Take the String representing the complete forecast in JSON Format and
         * pull out the data we need to construct the Strings needed for the wireframes
         *
         * Fortunately parsing is easy: constructor takes JSON string and converts it
         * into an Object heirarchy for us.
         */

        private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays)
            throws JSONException {

            // These are the names of the JSON objects that need to be extracted
            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_DESCRIPTION = "main";

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

            // OWM returns daily forecasts based upon the local time of the city that is being
            // asked for, which means that we need to know the GMT offset to translate this data
            // properly.

            // Since this data is also sent in-order and the first day is always the
            // current day, we're going to take advantage of that to get a nice
            // normalized UTC date for all of our weather.

            Time dayTime = new Time();
            dayTime.setToNow();

            // we start at the day returned by local time. Otherwise this is a mess.
            int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);

            // now we work exclusively in UTC
            dayTime = new Time();

            String[] resultStrs = new String[numDays];
            for(int i = 0; i<weatherArray.length();i++){
                // For now, using the format "Day, description, hi/low"
                String day;
                String description;
                String highAndLow;

                // Get the JSON object representing the day
                JSONObject dayForecast = weatherArray.getJSONObject(i);

                // The date/time is returned as long. We need to convert that
                // into someting human-readable, since most people won't read "1400356800" as
                // "this saturday"
                long dateTime;
                // Cheating to  convert this to UTC time, which is what we want anyhow
                dateTime = dayTime.setJulianDay(julianStartDay+i);
                day = getReadableDateString(dateTime);

                // description is in a child array called "weather", which is 1 element long.
                JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
                description = weatherObject.getString(OWM_DESCRIPTION);

                // Temperatures are in a child object called "temp". Try not to name variables
                // "temp" when working with temperature. It  confuses everybody.
                JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
                double high = temperatureObject.getDouble(OWM_MAX);
                double low = temperatureObject.getDouble(OWM_MIN);

                highAndLow = formatHighLows(high, low);
                resultStrs[i] = day + "-" + "-" + highAndLow;


            }

            for (String s : resultStrs){
                Log.v(LOG_TAG, "Forecast entry: " + s);
            }
            return resultStrs;
        }


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

            // These two need to be declared outside the try/catch
            // so that they  can be closed in the finally block.
            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;

            // Will contain the raw JSON response as a string
            String forecastJsonStr = null;

            String format = "json";
            String units = "metric";
            int numDays = 5;


            try {
                // Construct the URL for the OpenWeatherMap query
                // Possible parameters are available at OWM's forecast API page , at
                // http:// openweathermap.org/API#forecast
                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, BuildConfig.OPEN_WEATHER_MAP_API_KEY)
                        .build();

                URL url = new URL(builtUri.toString());

                Log.v(LOG_TAG, "Built URI " + builtUri.toString());

                // Create the request to OpenWeatherMap, and open the connection
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
                urlConnection.setRequestProperty("Accept", "*/*");
                urlConnection.setDoOutput(false);
                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 its JSON, adding a new line isn't necessary(it won't affect parsing)
                    // But it does make debugging a *lot* easier if you want to print out the complecated
                    // buffer for debugging
                    buffer.append(line + "\n");
                }

                if (buffer.length() == 0) {
                    // Stream was empty. No point in parsing.

                    return null;
                }


                forecastJsonStr = buffer.toString();

                Log.v(LOG_TAG, "Forecast JSON String: " + forecastJsonStr);

            } catch (IOException e) {
                Log.e(LOG_TAG, "Error", e);
                // If the code didn't succefully get the weather data, there is no point in attempting
                // to parse it.

                return null;
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException e) {
                        Log.e(LOG_TAG, "Error closing stream", e);
                    }
                }
            }

            try {
                return getWeatherDataFromJson(forecastJsonStr, numDays);
            } catch (JSONException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
                e.printStackTrace();
            }

            // This will only happen if there was an error getting or parsing the forecast.
            return null;

        }

        @Override
        protected void onPostExecute(String[] result){
            if (result != null){
                mForecastAdapter.clear();
                for (String dayForecastStr : result){
                    mForecastAdapter.add(dayForecastStr);
                }
                // New data is back from the server. Yep!!!
            }
        }

    }

logcat 错误信息:

08-26 11:37:55.432 2277-3097/com.example.android.sunshine E/FetchWeatherTask: No value for temp
org.json.JSONException: No value for temp
at org.json.JSONObject.get(JSONObject.java:389)
at org.json.JSONObject.getJSONObject(JSONObject.java:609)
at com.example.android.sunshine.ForecastFragment$FetchWeatherTask.getWeatherDataFromJson(ForecastFragment.java:208)
at com.example.android.sunshine.ForecastFragment$FetchWeatherTask.doInBackground(ForecastFragment.java:323)
at com.example.android.sunshine.ForecastFragment$FetchWeatherTask.doInBackground(ForecastFragment.java:119)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)

通过用 openweathermap api 中的真实数据替换虚拟数据,我无法弄清楚它为什么不更新。

我从 api 获得的这个 JSON 字符串:

V/FetchWeatherTask: Forecast JSON String: {"city":{"id":5375480,"name":"Mountain View","coord":{"lon":-122.083847,"lat":37.386051},"country":"US","population":0,"sys":{"population":0}},"cod":"200","message":0.0383,"cnt":5,"list":[{"dt":1472418000,"main":{"temp":25.84,"temp_min":24.15,"temp_max":25.84,"pressure":993.56,"sea_level":1031.58,"grnd_level":993.56,"humidity":71,"temp_kf":1.69},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],"clouds":{"all":0},"wind":{"speed":1.42,"deg":253},"rain":{},"sys":{"pod":"d"},"dt_txt":"2016-08-28 21:00:00"},{"dt":1472428800,"main":{"temp":25.84,"temp_min":24.57,"temp_max":25.84,"pressure":992.76,"sea_level":1030.67,"grnd_level":992.76,"humidity":68,"temp_kf":1.27},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"clouds":{"all":0},"wind":{"speed":1.4,"deg":260.004},"rain":{},"sys":{"pod":"n"},"dt_txt":"2016-08-29 00:00:00"},{"dt":1472439600,"main":{"temp":19.81,"temp_min":18.97,"temp_max":19.81,"pressure":992.9,"sea_level":1030.9,"grnd_level":992.9,"humidity":79,"temp_kf":0.85},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"clouds":{"all":0},"wind":{"speed":1.2,"deg":264.002},"rain":{},"sys":{"pod":"n"},"dt_txt":"2016-08-29 03:00:00"},{"dt":1472450400,"main":{"temp":14.24,"temp_min":13.82,"temp_max":14.24,"pressure":993.56,"sea_level":1031.77,"grnd_level":993.56,"humidity":92,"temp_kf":0.42},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"clouds":{"all":0},"wind":{"speed":1.48,"deg":291.5},"rain":{},"sys":{"pod":"n"},"dt_txt":"2016-08-29 06:00:00"},{"dt":1472461200,"main":{"temp":11.13,"temp_min":11.13,"temp_max":11.13,"pressure":993.2,"sea_level":1031.64,"grnd_level":993.2,"humidity":98,"temp_kf":0},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"02n"}],"clouds":{"all":8},"wind":{"speed":1.06,"deg":298.504},"rain":{},"sys":{"pod":"n"},"dt_txt":"2016-08-29 09:00:00"}]}
4

3 回答 3

1

OWM 已更改其 JSON 字符串,因此一些数组名称和对象名称也已更改,因此您需要使用新名称更新代码:

final String OWM_LIST = "list";
final String OWM_WEATHER = "weather";
final String OWM_TEMPERATURE = "main";
final String OWM_MAX = "temp_max";
final String OWM_MIN = "temp_min";
final String OWM_DESCRIPTION = "description";
于 2016-10-24T17:34:25.483 回答
0

在 Ashish 的启发下解决了这个问题。

添加:

JSONObject MainObject = dayForecast.getJSONObject(OWM_DESCRIPTION);

改变

JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);

至:

double temperatureObject = MainObject.getDouble(OWM_TEMPERATURE);

记住也要改变高低:

double high = MainObject.getDouble(OWM_MAX);

double low = MainObject.getDouble(OWM_MIN);

(OWM_MAX 出错,将字符串更改为,"temp_max"而不是"max"OWM_MIN 相同)

于 2016-09-29T12:50:43.210 回答
-1
org.json.JSONException: No value for temp

这意味着您没有temp从您的回复中收到“ ”值。

尝试在 log cat 中打印响应并检查。

于 2016-08-26T12:01:46.457 回答