2016-06-15 4 views
-2

openweathermap에서 날씨 데이터를 가져와 listview에서 볼 수있는 앱을 만들고있어 nullpointerexception 오류를 반환하고 계속 충돌합니다. 이것은 setListAdapter (adapter) 메소드를 호출하려고 할 때 발생합니다. 나는 며칠 동안이 문제를 독자적으로 디버깅하려고 노력했지만 문제를 찾을 수없는 것 같습니다. 내가 얻을 수있는 도움에 정말 감사드립니다. : 07 : 47.912 30849-30849/COMandroid custom adapter의 NullPointerException

여기

public class MainActivity extends ListActivity { 

    String mainUrl = "http://api.openweathermap.org/data/2.5/forecast/daily?q="; 
    String accessCode = "&APPID=4907e373098f091c293b36b92d8f0886"; 
    List<WeatherModel> weatherlist; 


    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     EditText getcityview = (EditText)findViewById(R.id.City); 
     Button searchButton = (Button) findViewById(R.id.search); 
     searchButton.setOnClickListener(search); 

    } 

    public String getcity(){ 

     EditText getcityview = (EditText)findViewById(R.id.City); 
     String Cityname = getcityview.getText().toString().trim(); 
     String result = deleteSpace(Cityname); 
     return result; 

    } 

    public String deleteSpace(String city){ 
     int loc = city.indexOf(" "); 
     if (loc != -1){ 
      String result = city.substring(0, loc) + city.substring(loc + 1); 
      return result; 
     } 
     else { 
      return city; 
     } 
    } 

    public void showForecast(){ 
     EditText getcityview = (EditText)findViewById(R.id.City); 
     if (!isEmpty(getcityview)) { 
      Log.d("Status:", "running"); 
      String cityName = getcity(); 
      String url = mainUrl + cityName + accessCode; 
      JsonParser Jparser = new JsonParser(); 
      Jparser.execute(url); 

     } 
     else { 
      Toast.makeText(getApplicationContext(), "No City entered", Toast.LENGTH_SHORT); 
     } 
    } 

    private boolean isEmpty(EditText etText) { 
     return etText.getText().toString().trim().length() == 0; 
    } 
    public View.OnClickListener search = new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      showForecast(); 
     } 
    }; 
    public void UpdateDisplay(){ 
     WeatherAdapter weatheradapter = new WeatherAdapter(this, R.layout.weather_item, weatherlist); 
     setListAdapter(weatheradapter); 
    } 


    private class JsonParser extends AsyncTask<String, String, JSONObject>{ 
     final String TAG = "JsonParser.java"; 

     InputStream is = null; 
     JSONObject jObj = null; 
     String json = ""; 
     HttpURLConnection UrlConnection = null; 
     List<WeatherModel> weatherList; 

     // make HTTP request 


     @Override 
     protected JSONObject doInBackground(String...params) { 
      try { 

       URL Url = new URL(params[0]); 
       UrlConnection = (HttpURLConnection) Url.openConnection(); 
       UrlConnection.connect(); 

       is = UrlConnection.getInputStream(); 

      } catch (UnsupportedEncodingException e) { 
       e.printStackTrace(); 
      } catch (ClientProtocolException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 

      try { 

       BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); 
       StringBuilder sb = new StringBuilder(); 
       String line = null; 
       while ((line = reader.readLine()) != null) { 
        sb.append(line + "\n"); 
       } 
       is.close(); 
       json = sb.toString(); 

      } catch (Exception e) { 
       Log.e(TAG, "Error converting result " + e.toString()); 
      } 

      // try parse the string to a JSON object 
      try { 
       jObj = new JSONObject(json); 
      } catch (JSONException e) { 
       Log.e(TAG, "Error parsing data " + e.toString()); 
      } 

      // return JSON String 
      Log.d("Confirmed", "Got JSON"); 
      return jObj; 
     } 


     @Override 
     protected void onPostExecute(JSONObject o) { 
      super.onPostExecute(o); 
      Log.d("Json:", o.toString()); 
      weatherList = WeatherParser.ParseFeed(o); 
      UpdateDisplay(); 

     } 


    } 

} 

여기 내 사용자 지정 어댑터 클래스의 내 주요 활동 클래스의

public class WeatherAdapter extends ArrayAdapter<WeatherModel> { 

private Context context; 
private List<WeatherModel> weatherlist; 
public WeatherAdapter(Context context, int resource, List<WeatherModel> objects){ 
    super(context, resource, objects); 
    this.context = context; 

    this.weatherlist = objects; 

} 

@Override 
public View getView(int position, View convertView, ViewGroup parent){ 
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    View view = inflater.inflate(R.layout.weather_item, parent, false); 

    WeatherModel weather = weatherlist.get(position); 
    TextView day = (TextView) view.findViewById(R.id.day); 
    TextView temperature = (TextView) view.findViewById(R.id.temperature); 
    TextView description = (TextView) view.findViewById(R.id.description); 

    day.setText(weather.getDate()); 
    temperature.setText(weather.getTemperature()); 
    description.setText(weather.getDescription()); 
    return view; 


} 

} 

여기에 내 로그 캣

06-15 (16)의 .example.android.weatherforecast D/상태 :: running 06-15 16 : 07 : 48.233 30849-6794/com.example .android.weatherforecast D/확인 됨 : JSON이 06-15 16 : 07 : 48.253 30849-30849/com.example.android.weatherforecast D/Json :: { "message": 0.0079, "list": [{ "구름": 36, "dt": 1466010000, "습도": 52, "압력": 995.17, "속도": 3.31, "deg": 150, "weather": [{ ""id ": 802,"icon "" "03 : 00": "03d", "description": "흩어져", "main": "Clouds}}", "temp": { "아침": 297.43, "min": 287.68, "night": 287.68, 295.43, "day": 297.43}}, { "구름": 0, "dt": 14660964 ...... 06-15 16 : 07 : 48.253 30849-30849/com.example.android.weatherforecast D/확인 됨 : JSON 구문 분석 06-15 16 : 07 : 48.273 30849-30849/com.example.android.weatherforecast D/AndroidRuntime : VM 종료 06-15 16 : 07 : 48.273 30849-30849/com.example.android.weatherforecast W/dalvikvm : threadid = 1 : 발견되지 않은 예외 (그룹 = 0x4181ada0)로 종료하는 스레드 06-15 16 : 07 : 48.293 30849-30849/com.example.android.weatherforecast E/AndroidRuntime : 치명적인 예외 : 주 프로세스 : com. example.android.weatherforecast, PID : 30,849 로이드에서 android.widget.ListView.setAdapter (ListView.java:486)에서 android.widget.ArrayAdapter.getCount (ArrayAdapter.java:330)에서 java.lang.NullPointerException이 .app.ListActivity.setListAdapter (ListActivity.java:265) at com.example.android.weatherforecast.MainActivity.UpdateDisplay (MainActivity.java:89) at com.example.android.weatherforecast.MainActivity $ JsonParser.onPostExecute (MainActivity.java:156) 에서 com.example.android.weatherforecast.MainActivity $ JsonParser.onPostExecute (MainActivity.java:93) android.os.AsyncTask.finish (AsyncTask.java:632)에서 android.os.AsyncTask.access $ 600 (AT android.os.Looper.loop에서 android.os.AsyncTask $ InternalHandler.handleMessage (AsyncTask.java:645) android.os.Handler.dispatchMessage (Handler.java:102에서 )에서 AsyncTask.java:177) (Looper.java:157) at android.app.ActivityThread.main (ActivityThread.java:5356) at java.lang.reflect.Method.invokeNative (네이티브 메소드) at java.lang.reflect.Method.invoke (Method .java : 515) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run (ZygoteInit.java:1265) at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1081) at dalvik.system.NativeStart.메인은 (기본 방법)

답변

1

귀하는 MainActivity에 1을 입력하고 JsonParser에 2를 입력했습니다.
MainActivity의 weatherList가 할당되지 않았으므로 NullPointerException이 발생합니다.

당신은 두 변수를 제거하고 JsonParser 할의 수 :

@Override 
protected void onPostExecute(JSONObject o) { 
    super.onPostExecute(o); 
    Log.d("Json:", o.toString()); 
    UpdateDisplay(WeatherParser.ParseFeed(o)); 
} 

귀하의 방법 UpdateDisplay는 다음과 같이 수 :

public void UpdateDisplay(List<WeatherModel> weatherlist){ 
    WeatherAdapter weatheradapter = new WeatherAdapter(this, R.layout.weather_item, weatherlist); 
    setListAdapter(weatheradapter); 
} 
+0

감사합니다! 이것은 나를 위해 일했다! !! 정말 감사합니다. – majestyc54

2

것은

당신이

private List<WeatherModel> weatherlist; 

을 선언했지만이 초기화되지 않습니다,이 여기

WeatherModel weather = weatherlist.get(position); 

예외의 이유가 있으니주의하시기 바랍니다 그래서 객체 weatherlist은 null 참조를 가리키고 있습니다 ...