简体   繁体   中英

facebook4j graph api limiting the no of comments to 25 on a post

I'm trying to fetch all the comments posted for a particular post on the fan page example "narendramodi" But some how the facebook graph API is limiting the number of comments to 25 , as my application crashes with "Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 25, Size: 25"

I'm using paging and fetchNext , but still it is not working.

Here is my code -

public class Facebooktest { 

static Facebook facebook;

        public static void main(String[] args) throws FacebookException, IOException {
        // Make the configuration builder
        ConfigurationBuilder confBuilder = new ConfigurationBuilder(); 
        confBuilder.setDebugEnabled(true);

        // Set application id, secret key and access token 
        confBuilder.setOAuthAppId("MyID"); 
        confBuilder.setOAuthAppSecret("MyAppSecret"); 

        confBuilder.setOAuthAccessToken("MyAccessToken");

        // Set permission 
        confBuilder.setOAuthPermissions("email,publish_stream, id, name, first_name, last_name, generic"); 
        confBuilder.setUseSSL(true); 
        confBuilder.setJSONStoreEnabled(true);

        // Create configuration object 
        Configuration configuration = confBuilder.build();

        // Create facebook instance 
        FacebookFactory ff = new FacebookFactory(configuration); 
        facebook = ff.getInstance();

        ResponseList<Post> results = facebook.getPosts("narendramodi");

        //facebook.getFriends(new Reading().fields("gender"));
        /*System.out.println("success");
        System.out.println(facebook.getMe().getFirstName());*/      

        String userId="";

        for (Post post : results) {
            System.out.println(post.getMessage() +"===="+  + post.getSharesCount() +"====="+ post.getLikes().size()); // Gives a max of 25 likes


           List<Comment> userComments =  getComments(post); 


            for (int j = 0; j < userComments.size(); j++) {

             userId=post.getComments().get(j).getFrom().getId();
             User user = facebook.getUser(userId);   

             System.out.println(user.getFirstName() + "---- "+ post.getComments().get(j).getLikeCount() +"---- "+ user.getHometown() + "======" + userComments.get(j).getMessage());

            }
        }

    }

    public static  List<Comment> getComments(Post post) {
        List<Comment> fullComments = new ArrayList<>();
        try {

            PagableList<Comment> comments = post.getComments();
            Paging<Comment> paging;
            do {
                for (Comment comment: comments)
                    fullComments.add(comment);


                paging = comments.getPaging();
            } while ((paging != null) && 
                    ((comments = facebook.fetchNext(paging)) != null));

        } catch (FacebookException ex) {
            Logger.getLogger(Facebook.class.getName())
                    .log(Level.SEVERE, null, ex);
        }

        return fullComments;
    }

}

Also How to get the total no of likes of the main "post" posted on the page. ? As this part of the code (post.getLikes().size()) gives a max of 25 likes !

Thanks In advance :)

First number of returned items is limited to 25 by default and maxed at 250. So you need to add a "limit(250)" param to your call.

Second you need to return all comments/likes by adding a "filter(stream)" param to your call for comments or likes. Facebook "hides" some comments or likes due to a low "story" value.

Finally to get a total count you need to add a "summary(true)" param to your call for comments or likes. This will give to a "summary" key, with a "total_count" key with a value for the total count of all comments or likes. (If you omit the filter param above it will only count the visible ones)

See my comments here for more detailed info. Facebook Graph Api : Missing comments

Finally found a workaround to this. As suggested by frank I set the limit in the URL and retrived the data as a json object.

Here is my code -

   public class FacebookJson { 

    static Facebook facebook;
    public static void main(String[] args) throws FacebookException, IOException {
        // Make the configuration builder
        ConfigurationBuilder confBuilder = new ConfigurationBuilder(); 
        confBuilder.setDebugEnabled(true);

        // Set application id, secret key and access token 
        confBuilder.setOAuthAppId("MyAPPid"); 
        confBuilder.setOAuthAppSecret("MyAPPSecret"); 

        confBuilder.setOAuthAccessToken("AccessToken");
        //397879687034320|883YXTum1HBJMEbWKbsfq-80pV0
        // Set permission 
        confBuilder.setOAuthPermissions("email,publish_stream, id, name, first_name, last_name, generic"); 
        confBuilder.setUseSSL(true); 
        confBuilder.setJSONStoreEnabled(true);


        // Create configuration object 
        Configuration configuration = confBuilder.build();

        // Create facebook instance 
        FacebookFactory ff = new FacebookFactory(configuration); 
        facebook = ff.getInstance();

        ResponseList<Post> results1 = facebook.getPosts("narendramodi" , new Reading().limit(5));
         for (Post post : results1) {


        System.out.println(post.getMessage() +"===="+  + post.getSharesCount() + "====" + "====" + post.getId());           

      URL url = new URL("https://graph.facebook.com/{PostId}/comments?fields=parent,message,from,created_time,can_comment&filter=stream&limit=100?access_token={accesstoken}");
         try (InputStream is = url.openStream();
              JsonReader rdr = Json.createReader(is)) {

             JsonObject obj = (JsonObject) rdr.readObject();
             JsonArray results = (JsonArray) obj.get("data");
             for (JsonObject result : results.getValuesAs(JsonObject.class)) {
                 System.out.print(result.getJsonObject("from").getString("name"));
                 System.out.print(": ");
                 System.out.print(result.getJsonObject("from").getString("id"));
                 System.out.print(": ");
                 System.out.println(result.getString("message"));
                 System.out.println("-----------");
                 System.out.println(result.getString("id"));
                 System.out.println("-----------");
                 System.out.println(result.getString("created_time"));
             }


         }
        } 

    }

}

Hope this helps the users , but still I want to know how to set the limit in the code of my question. ! If anyone can help it will be grateful.

And thank you once again frank. :)

Paging paging; do {

            for (Comment comment: comments)
                fullComments.add(comment);
            paging = comments.getPaging();
        }while((paging!=null)&&((feeds=facebook.fetchNext(paging))!=null));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM