当我调用此构造函数来解析某些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);
}
}
}
它看起来不像uriMap已初始化? –
'我以为Android/Java会自动初始化任何类字段'!为什么呢?这只会占用记忆没有理由:) –