将值放入地图时为空

时间:2011-11-04 14:54:35

标签: android

当我调用此构造函数来解析一些JSON时,我在尝试将值插入uriMap时遇到了一个nullpointer异常。我认为Android / Java会自动初始化任何类字段。此外,当我调试应用程序时,uriMap的值显示为null。在开始使用它之前,我没有看到任何初始化地图的方法。我做错了什么?

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);
    }
    }
}

2 个答案:

答案 0 :(得分:3)

您必须自己初始化地图。

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

答案 1 :(得分:2)

您永远不会初始化Uri地图。你需要初始化它。