When I call this constructor to parse some JSON I’m getting a nullpointer exception when trying to insert the values into uriMap. I thought Android / Java would automatically initialize any class fields. Also when I debug the app the value of the uriMap is showing as null. I don’t see any way to initialize the map before I start using it. What am I doing wrong?
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);
}
}
}
You have to initialize the map yourself.