Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

justin z
justin z
11,042 Points

JSONException caught: no value for temperatureMax...

Hey guys, whenever I try to run the weather app I get the following error: 06-07 11:29:52.259 13517-13540/teamtreehouse.com.stormy E/MainActivity: Exception caught: org.json.JSONException: No value for temperatureMax at org.json.JSONObject.get(JSONObject.java:389) at org.json.JSONObject.getDouble(JSONObject.java:444) at teamtreehouse.com.stormy.ui.MainActivity.getDailyForecast(MainActivity.java:190) at teamtreehouse.com.stormy.ui.MainActivity.parseForecastDetails(MainActivity.java:175) at teamtreehouse.com.stormy.ui.MainActivity.access$400(MainActivity.java:37) at teamtreehouse.com.stormy.ui.MainActivity$2.onResponse(MainActivity.java:115) at okhttp3.RealCall$AsyncCall.execute(RealCall.java:133) at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32) 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) 06-07 11:30:16.419 13517-13517/teamtreehouse.com.stormy V/ActivityThread: updateVisibility : ActivityRecord{e091dd0 token=android.os.BinderProxy@3e56d68 {teamtreehouse.com.stormy/teamtreehouse.com.stormy.ui.MainActivity}} show : true

I'm not sure why it can't get the value for temperatureMax, as the code in my MainActivity seems to be correct. Here's the code for my MainActivity:

public class MainActivity extends AppCompatActivity {

    public static final String current = MainActivity.class.getSimpleName();

    @BindView(R.id.timeTextView) TextView mTimeLabel;
    private TextView mTemperatureLabel;
    @BindView(R.id.humidityValue) TextView mHumidityValue;
    @BindView(R.id.precipValue) TextView mPrecipValue;
    @BindView(R.id.textView2) TextView mSummaryLabel;
    @BindView(R.id.iconImageView) ImageView mIconImageView;
    @BindView(R.id.refreshImageView) ImageView mRefreshImage;
    @BindView(R.id.progressBar) ProgressBar mProgressBar;
    private Forecast mForecast;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        mProgressBar.setVisibility(View.INVISIBLE);


        mTemperatureLabel= (TextView) findViewById(R.id.tempTextView);
        mRefreshImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getForecast();
            }
        });

        getForecast();

        Log.d(current, "Main UI code is running!");
    }

    private void getForecast() {
        String apiKey = "27974c4bc33201748eaf542a6769c3b7";
        double latitude = 37.8267;
        double longitude = -122.423;
        String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
                "/" + latitude + "," + longitude;

        if (isNetworkAvailable()) {

            toggleRefresh();
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(forecastUrl)
                    .build();

            Call call = client.newCall(request);
            call.enqueue(new Callback() {

                @Override
                public void onFailure(Call call, IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            toggleRefresh();
                        }
                    });
                    alertUserAboutError();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            toggleRefresh();
                        }
                    });

                    try {
                        String jsonData = response.body().string();
                        Log.v(current, jsonData);
                        if (response.isSuccessful()) {
                            mForecast = parseForecastDetails(jsonData);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    updateDisplay();
                                }
                            });

                        } else {
                            alertUserAboutError();
                        }
                    }
                    catch (IOException e) {
                        Log.e(current, "Exception caught: ", e);
                    }
                    catch (JSONException e) {
                        Log.e(current, "Exception caught: ", e);
                    }

                }
            });
        }
        else {
            Toast.makeText(this,"Network Unavailable",
                    Toast.LENGTH_LONG).show();
        }
    }

    private void toggleRefresh() {
        if(mProgressBar.getVisibility()==View.INVISIBLE) {

            mProgressBar.setVisibility(View.VISIBLE);
            mRefreshImage.setVisibility(View.INVISIBLE);
        }
        else {

            mProgressBar.setVisibility(View.INVISIBLE);
            mRefreshImage.setVisibility(View.VISIBLE);

        }

    }

    private void updateDisplay() {
       Current current = mForecast.getCurrent();

        mTemperatureLabel.setText(current.getTemperature()+"");
        mTimeLabel.setText("At "+ current.getFormattedTime()+" it will be");
        mHumidityValue.setText(current.getHumidity()+"");
        mPrecipValue.setText(current.getPrecipChance()+"");
        mSummaryLabel.setText(current.getSummary());
        Drawable drawable = getResources().getDrawable(current.getIconId());
        mIconImageView.setImageDrawable(drawable);
    }


    private Forecast parseForecastDetails(String jsonData) throws JSONException {
        Forecast fc = new Forecast();
        fc.setCurrent(getCurrentDetails(jsonData));
        fc.setHourlyForecast(getHourlyForecast(jsonData));
        fc.setDailyForecast(getDailyForecast(jsonData));
        return fc;

    }

    private Day[] getDailyForecast(String jsonData) throws JSONException {
        JSONObject forecast = new JSONObject(jsonData);
        String timezone = forecast.getString("timezone");
        JSONObject daily = forecast.getJSONObject("hourly");
        JSONArray data = daily.getJSONArray("data");
        Day[] days = new Day[data.length()];
        for (int i=0;i<data.length();i++) {
            JSONObject jsonDay = data.getJSONObject(i);
            Day day = new Day();
            day.setTime(jsonDay.getLong("time"));
            day.setTemperatureMax(jsonDay.getDouble("temperatureMax"));
            day.setSummary(jsonDay.getString("summary"));
            day.setIcon(jsonDay.getString("icon"));
            day.setTimeZone(timezone);
            days[i]=day;
        }
        return days;
    }

    private Hour[] getHourlyForecast(String jsonData) throws JSONException {
        JSONObject forecast = new JSONObject(jsonData);
        String timezone = forecast.getString("timezone");
        JSONObject hourly = forecast.getJSONObject("hourly");
        JSONArray data = hourly.getJSONArray("data");
        Hour[] hours = new Hour[data.length()];
        for (int i=0;i<data.length();i++) {
            JSONObject jsonHour = data.getJSONObject(i);
            Hour hour = new Hour();
            hour.setTime(jsonHour.getLong("time"));
            hour.setTemperature(jsonHour.getDouble("temperature"));
            hour.setSummary(jsonHour.getString("summary"));
            hour.setIcon(jsonHour.getString("icon"));
            hour.setTimeZone(timezone);
            hours[i]=hour;
        }
        return hours;
    }


    private Current getCurrentDetails(String jsonData) throws JSONException {
        JSONObject forecast = new JSONObject(jsonData);
        String timezone = forecast.getString("timezone");
        Log.i(current, "From JSON: " + timezone);
        JSONObject currently = forecast.getJSONObject("currently");

        Current cw = new Current();
        Long time = currently.getLong("time");
        String icon = currently.getString("icon");
        double temperature = currently.getDouble("temperature");
        double humidity = currently.getDouble("humidity");
        double precipChance = currently.getDouble("precipProbability");
        String summary = currently.getString("summary");
        cw.setTime(time);
        cw.setIcon(icon);
        cw.setTemperature(temperature);
        cw.setHumidity(humidity);
        cw.setPrecipChance(precipChance);
        cw.setSummary(summary);
        cw.setTimeZone(timezone);
        Log.e(current, cw.getFormattedTime());
        return cw;
    }


    private boolean isNetworkAvailable() {
        ConnectivityManager manager = (ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        boolean isAvailable = false;
        if (networkInfo != null && networkInfo.isConnected()) {
            isAvailable = true;
        }

        return isAvailable;
    }

    private void alertUserAboutError() {
        AlertDialogFragment dialog = new AlertDialogFragment();
        dialog.show(getFragmentManager(), "error_dialog");
    }

    @OnClick(R.id.dailyButton)
    public void startDailyActivity(){
        Intent intent = new Intent(this, DailyForecastActivity.class);
        intent.putExtra("Forecast",mForecast.getDailyForecast());
        startActivity(intent);


    }



}

Someone who had an identical problem as me posted a question about this before, https://teamtreehouse.com/community/exception-caught-no-value-for-temperaturemax but they weren't able to find a solution. Any help would be much appreciated.

[MOD: edited code block - sh]

1 Answer

Hi Justin,

This issue is an intermittent problem with the JSON that gets pulled back from forecast.io. I left a couple of workarounds in the post you linked - have you tried those?

The problem is that forecast.io sometimes omits the key/value pair from the data feed. So, when you try to access a value by using its key, this fails with the error you're experiencing. There's nothing wrong with your code; it is the JSON being downloaded that contains the problem.

Have a look at the solutions suggested in that other post - I'm afraid I have nothing more to add since then.

Steve.

justin z
justin z
11,042 Points

Ok, thanks. It's nice to know there is nothing wrong with the code. Hopefully most APIs are more stable than forecast.io, because it kind of defeats the point of using an API if it can't consistently deliver data.