问题描述
- 在列表中保存对象出现exception
-
创建了名为Placeslist的类,想对其列表,在里面保存对象,但是报出异常:**Android.java.lang.NullPointerException**placeslist class: public class Placeslist { @Key public String status; @Key public String id; @Key public String name; @Key public String reference; @Key public double lat; @Key public double lon; public Placeslist(String status,String id,String name,String reference,double lat,double lon) { // TODO Auto-generated constructor stub this.status=status; this.id=id; this.name=name; this.reference=reference; this.lat=lat; this.lon=lon; }
在列表中保存对象:
Placeslist placeslist=null; String data = EntityUtils.toString(response.getEntity()); JSONObject jsonObj = new JSONObject(data); List<Placeslist>places=null; JSONArray results = jsonObj.getJSONArray("results"); for (int i = 0; i < results.length(); i++) { JSONObject result = results.getJSONObject(i); String name = result.getString("name"); String id = result.getString("id"); String reference = result.getString("reference"); JSONObject latitudes = result.getJSONObject("geometry") .getJSONObject("location"); double lon = latitudes.getDouble("lng"); double lat = latitudes.getDouble("lat"); placeslist=new Placeslist("OK", id, name, reference, lat, lon); places.add(placeslist); }
解决方案
你忘了
places = new ArrayList<PlacesList>();
或者
places = new LinkedList<PlacesList>();
List是一个接口interface ,不能直接用来创建对象,可以换成子类实现。
时间: 2024-09-16 04:44:13