2014-07-20 62 views
0

我正在使用Twitter4j構建客戶端以獲取輸入搜索詞的推文。我還試圖爲用戶提供設施,以便在結果中輸入他想要的推文數量。如何使用twitter4j獲取固定數量的推文

我知道,我們可以設置要與查詢的setCount()方法每頁返回鳴叫的次數:

Query q = new Query(searchTerm); 
q.setCount(maxTweets);  

但是,如果我給值1作爲maxTweets,它返回2個鳴叫。

更新:經過進一步研究,我發現它每個搜索返回1個額外的推文。所以我給1作爲maxTweets值,它返回2推文。如果我將2作爲maxTweets值給出,則返回3條推文等等。

我不確定我在哪裏錯了,但請讓我知道,如果有一種方法,我可以通過twitter4j獲得固定數量的推文。

任何指導都會有所幫助。

回答

1

當你寫的這

Query q = new Query(searchTerm); 

覺得作爲其中包含結果符合您查詢的量一個提交頁面。但是可能會有更多的頁面。

當您設置

q.setCount(maxTweets); 

它會給你帶來maxTweets每頁鳴叫的量。在你的情況下,2,因爲有兩個頁面與你的查詢相匹配,你每頁選擇一條推文。

你可以做什麼,嘗試用do-while循環來處理它。

 Query q = new Query(searchTerm); 
     QueryResult result; 
     int tempUSerInput = 0; //keep a temp value 
     boolean flag = false; 

     do { 
      result = twitter.search(query); 
      List<Status> tweets = result.getTweets(); 

      tempUSerInput = tempUSerInput + tweets.size(); 

      if(tempUSerInput >= realyourUserInput) // you have already matched the number 
       flag = true;    //set the flag 

     } 

     while ((query = result.nextQuery()) != null && !flag); 


     // Here Take only realyourUserInput number 
     // as you might have taken more than required 

     List<Status> finaltweets = new ArrayList(); 

     for(int i=0; i<realyourUserInput; i++) 
      finaltweets.add(tweets.get(i)); //add them to your final list 
+0

感謝user3764893的幫助。我不確定這是否是獲取固定數量的推文的唯一方式,但它解決了我的問題。謝謝!! – sf9251

+0

我希望你明白了主意。我很樂意提供幫助。 – user3764893

相關問題