I am using mongodb to store information of users. I wanted to create a method that get the information from the db, creates Player objects and inserts them in an array of Players.
this is the following method
public ArrayList<Player> getArrayOfPlayers(){
ArrayList<Player> savePlayers = new ArrayList<Player>();
DB db = connectToMongo();
DBCollection coll = db.getCollection("players");
DBCursor cursor = coll.find();
while(cursor.hasNext()) {
String tempName = (String)cursor.next().get("name");
String tempSession = (String)cursor.next().get("session");
String tempStringScore = (String)cursor.next().get("score");
int tempScore = Integer.parseInt(tempStringScore);
Player player = new Player(tempName,tempSession,tempScore);
savePlayers.add(player);
}
return savePlayers;
}
I have 4 users stored in the db and when I 'm trying to first call the method and then print the names for example I'm getting an exception. I used a try-catch outside the method's while and I caught the exception, but then it printed the name of the first user only. It seems that it throws the exception in the second iteration.
Here is the message with the exception that I am receiving.
java.lang.RuntimeException: no more
com.mongodb.DBApiLayer$Result.next(DBApiLayer.java:394)
com.mongodb.DBApiLayer$Result.next(DBApiLayer.java:360)
com.mongodb.DBCursor._next(DBCursor.java:445)
com.mongodb.DBCursor.next(DBCursor.java:525)
machine.DAOMongodb.getArrayOfPlayers(DAOMongodb.java:74)
machine.testDB.doGet(testDB.java:43)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
Calling the cursor.next()
method you get the next element and increment cursor position.
You call cursor.next()
3 times for each iteration so at second iteration you have "no more" element in the cursor.
Save the element in a variable local to the iteration:
while(cursor.hasNext()) {
DBObject tobj = cursor.next();
String tempName = (String)tobj.get("name");
String tempSession = (String)tobj.get("session");
String tempStringScore = (String)tobj.get("score");
int tempScore = Integer.parseInt(tempStringScore);
Player player = new Player(tempName,tempSession,tempScore);
savePlayers.add(player);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With