-1

Below is the code to retrieve last 10 posts from DB and return a List.

I am facing Null Pointer exception at posts.add(doc) line.

Am I doing anything wrong?

public List<Document> findByDateDescending(int limit) {

    List<Document> posts = null;
    Bson sort = Sorts.descending("date");
    MongoCursor<Document> cursor =  postsCollection.find().sort(sort).limit(limit).iterator();
    try{
        while(cursor.hasNext()){
            System.out.println("Whats wrong with code");
            Document  doc = cursor.next();
            System.out.println(doc);
            posts.add(doc); ----Null pointer exception
        }
    }
    finally {
       cursor.close();
    }
    return posts;
}
ekad
  • 14,436
  • 26
  • 44
  • 46
Siva
  • 1

1 Answers1

0

You defined posts but never assigned anything to it so it's still null. Something like this should work.

List<Document> posts = new List<>();
Jacob Wang
  • 4,411
  • 5
  • 29
  • 43
  • Thank u for ur response.I am adding bson document "doc" in each iteration to posts list..If any code change is to be done help me. – Siva Aug 23 '15 at 03:20
  • `posts` is null. you can't add/append anything to null. I think you want to initiate `posts` to be an empty **List**. See my updated answer – Jacob Wang Aug 26 '15 at 02:36