0

I am working with Facebook API using the restfb library of Java. I wrote a code to get a user's timeline posts but I am keep getting the java.lang.NullPointerException error.

import com.restfb.Connection;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.types.Page;
import com.restfb.types.Post;
import com.restfb.types.User;
import java.util.List;

public class FacebookAPI {


    public static void main(String[] args) {
        String accessToken = ""; //No I did not forget that
        FacebookClient fbClient = new DefaultFacebookClient(accessToken);
        //For some reasons the "DefaultFacebookClient" object is shown strikethrough formated in my IDE, idk what it means.

        Page page = fbClient.fetchObject("BillGates", Page.class);
        Connection<Post> postFeed = fbClient.fetchConnection(page.getId()+"/feed",Post.class);
            for(List<Post> postPage : postFeed){
                for(Post aPost : postPage){
                    System.out.println(aPost.getFrom().getName());
                    System.out.println("-->"+aPost.getMessage());
                    System.out.println("fb.com/"+aPost.getId());

                }
            }

    }

}

Output:

Exception in thread "main" java.lang.NullPointerException at facebookapi.FacebookAPI.main(FacebookAPI.java:34)

Line 34 is the second for loop.

Shad
  • 1

1 Answers1

0

The official facebook documentation say:

For Posts on a Page:

Any valid access token can read posts on a public Page, but responses will not include User information.

So restfb will return NULL. And if you try to getName() to that will lead to NullPointerException.

Rcordoval
  • 1,792
  • 1
  • 15
  • 24