我收到null pointer exception
的错误,但根据我的检查,循环流程正常。
我在这段代码上收到错误
bitmap = BitmapFactory.decodeResource(getResources(), MapId.getId(mapName));
mIndiaBitmapLoadedListener.onIndiaBimapLoaded(bitmap);
map.setImageBitmapReset(bitmap, true);
这是我的MapId
班级
public class MapId
{
public static HashMap<String,Integer> mapids = new HashMap<String, Integer>();
public static void setHashMap()
{
mapids.put("Political Map",R.drawable.indiapoliticalbig);
mapids.put("Physical Map",R.drawable.physicalmap);
mapids.put("Railway Map", R.drawable.railwaymap);
mapids.put("Road Map", R.drawable.roadmap);
mapids.put("Tourist Map", R.drawable.touristmap);
}
public static int getId(String stateName)
{
return mapids.get(stateName);
}
}
这是我的Error log
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference
at com.compare.IndiaAtlas.MapId.getId(MapId.java:58)
at com.compare.IndiaAtlas.IndiaFragment.onCreateView(IndiaFragment.java:62)
at android.app.Fragment.performCreateView(Fragment.java:2053)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:894)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.app.BackStackRecord.run(BackStackRecord.java:834)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1454)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:447)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5343)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
我们在sethashmap()
Railway Map
,Road Map
&amp;添加了三个新条目。 Tourist Map
这些是获得error
,但之前的条目物理和政治地图正在正常运行。
答案 0 :(得分:1)
我认为你应该像这样初始化你的地图:
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class MapId {
private static Map<String, Integer> mapids;
static {
mapids = new HashMap<String, Integer>();
mapids.put("Political Map", R.drawable.indiapoliticalbig);
mapids.put("Physical Map", R.drawable.physicalmap);
mapids.put("Railway Map", R.drawable.railwaymap);
mapids.put("Road Map", R.drawable.roadmap);
mapids.put("Tourist Map", R.drawable.touristmap);
mapids = Collections.unmodifiableMap(mapids);
}
public static int getId(String stateName) {
if (mapids.containsKey(stateName)) {
return mapids.get(stateName);
}
return 0;
}
}
然后使用:
MapId.getId("Tourist Map");