-3

임 햇빛 앱을 빌드하는 udacity android 튜토리얼에서 날씨 정보를 업데이트하는 새로 고침 버튼을 만들었습니다. 클릭하면 정보가 업데이트되지 않고 JSONException이 발생합니다. _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!!! 
      } 
     } 

    } 

로그 캣 오류 메시지 :

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) 

나 실시간으로 더미 데이터를 repalcing하여이 업데이트되지 않는 이유를 이해할 수 없다 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"}]} 
+0

는 온도에 대한 JSON 처음 OWM_DESCRIPTION 개체 수 –

+1

게시 .. 무슨 뜻 나는 OWM_TEMPERATURE를 얻기 전에 OWM_DESCRIPTION 객체를 가져야한다 ?? –

답변

-1
org.json.JSONException: No value for temp 

그것은 당신이 당신의 응답의 'temp "값을받지 못한 것을 의미한다.

log cat 및 check에 응답을 인쇄 해보십시오.

+0

귀하의 의견 JSON을 게시 한 다음 – Ashish

+0

메신저 미안 해요, 난 이해가 안 ... 당신의 구문 분석에 문제가 당신의 임시 변수를 가져올 –

+0

// Doom로 처리 JSONObject MainObject = objecttwo.getJSONObject (OWM_DESCRIPTION); JSONObject temperatureObject = MainObject.getJSONObject (OWM_TEMPERATURE); // dayForcast 개체를 사용하여 temperatureObject를 가져 오지 않음 – Ashish

0

Ashish에서 영감을 얻어 해결했습니다.

추가 :

double temperatureObject = MainObject.getDouble(OWM_TEMPERATURE); 

이 너무 높고 낮은를 변경해야합니다 :

JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); 

JSONObject MainObject = dayForecast.getJSONObject(OWM_DESCRIPTION); 

변화

double high = MainObject.getDouble(OWM_MAX); 

double low = MainObject.getDouble(OWM_MIN); 

1

OWM (OWM_MAX 대신 "max""temp_max"로 변경 문자열, OWM_MIN에 대한 동일로 오류가 발생했습니다는) 자신의 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"; 
관련 문제