首页 > 解决方案 > 使用 Java 的 Facebook API - NullPointerException 错误

问题描述

我正在使用 Java 的 restfb 库处理 Facebook API。我编写了一个代码来获取用户的时间线帖子,但我不断收到 java.lang.NullPointerException 错误。

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());

                }
            }

    }

}

输出:

facebookapi.FacebookAPI.main(FacebookAPI.java:34) 的线程“主”java.lang.NullPointerException 中的异常

第 34 行是第二个 for 循环。

标签: javafacebook-graph-apinullpointerexceptionrestfb

解决方案


官方facebook文档说:

对于页面上的帖子:

任何有效的访问令牌都可以阅读公共主页上的帖子,但响应不会包含用户信息。

所以 restfb 会返回NULL。如果您尝试 getName() 到那将导致 NullPointerException。


推荐阅读