2011-11-04 55 views
-1

当我调用此构造函数来解析某些JSON时,尝试将值插入到uriMap中时出现空指针异常。我认为Android/Java会自动初始化任何类字段。另外,当我调试应用程序时,uriMap的值显示为空。在我开始使用它之前,我没有看到任何方式来初始化地图。我究竟做错了什么?将值放入地图时的空点

public class ServiceLocator { 
    private static final String TAG = ServiceLocator.class.getSimpleName(); 
    Map <String,Uri>uriMap; 

    public ServiceLocator(JSONObject json){ 
    try { 
     json = (JSONObject) new JSONTokener(testJson).nextValue(); 
     JSONArray locations = json.getJSONArray("data"); 
     int len = locations.length(); 
     for(int i=0; i<len; i++){ 
      JSONObject obj = locations.getJSONObject(4); 
      String name = obj.getString("name"); 
      Uri uri = Uri.parse(obj.getString("url")); 
      if(name != null && uri != null){ 
       uriMap.put(name, uri); 
      } 
      Log.d(TAG, "Inserted key(" + name + "),value(" + uri.toString() + ") into tempMap"); 
     } 
    } catch (JSONException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (NullPointerException e){ 
     Log.d(TAG, "Error inserting into map", e); 
    } 
    } 
} 
+0

它看起来不像uriMap已初始化? –

+1

'我以为Android/Java会自动初始化任何类字段'!为什么呢?这只会占用记忆没有理由:) –

回答

3

你必须自己初始化地图。

Map <String,Uri> uriMap = new HashMap <String,Uri>(); 
+0

谢谢,这是一个失败!对我而言... – LowDev1

2

您从不初始化Uri映射。你需要初始化它。