Question

I have been trying to code a new class in JAVA where I use a Map and HashMap to relay information to different classes rather than declaring the Map locally in every class.

I have created a new class "GetRoom.java" which has 4 different methods:

  • void addRoom(int id, Room room)
  • Room byID(int id)
  • boolean containsID(int id)
  • Room doIexist()

The code is as follows:

private static Map<Integer, Room> hotelRooms = new HashMap<Integer, Room>();

public static void addRoom(int id, Room room){
    hotelRooms.put(id, room);
}

public static Room byID(int id){
    return hotelRooms.get(id);
}

public static Room doIexist(){
    return hotelRooms.get(5);
}

public static boolean containsID(int id){
    return hotelRooms.containsKey(id);
}

If I use the byID function in any other class it will return NullPointerException, whereas, if I use the doIexist function then it will return the Room ID 5. When calling hotelRooms.size() I can see that I have filled it with 42 rooms before but can not reference them outside of GetRoom.java

Any help is much appreciated!

edit: This is where I call the code from:

public static void Compose(ServerHandler Client, User theUser, Environment Server) throws Exception
{
    User CurrentUser = Client.GetSession();
    int RoomId = CurrentUser.CurrentRoomId;
    Channel Socket = Client.Socket;
    Room R = GetRoom.byID(RoomId); // If I change this to GetRoom.doIExist(); it will work

    ServerMessage HeightMap = new ServerMessage(ServerEvents.HeightMap1);
    HeightMap.writeUTF(R.GetModel().getMap());
    HeightMap.Send(Socket);

    ServerMessage RelativeMap = new ServerMessage(ServerEvents.HeightMap2);
    String Map = R.GetModel().SerializeRelativeMap;
    RelativeMap.writeUTF(Map);
    RelativeMap.Send(Socket);       
}

StackTrace:

java.lang.NullPointerException
    at messages.outgoing.rooms.LoadMapsMessageComposer.Compose(LoadMapsMessageComposer.java:30)
    at messages.incoming.rooms.LoadMapsMessageEvent.run(LoadMapsMessageEvent.java:28)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

LoadMapsMessageComposer.java:30 is the line that has

HeightMap.writeUTF(R.GetModel().getMap());

Was it helpful?

Solution

The problem is that while you may have several rooms added to your map, you don't have a room corresponding to the currentRoomId. That means that get(id) and thus byID are returning null, and then you try to call a method on that null value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top