这是我第一次使用 Twitter API。我正在编写一个基本应用程序,当用户键入一个短语时,它会返回带有该短语的最后 15 条推文。如果他们键入用户名并单击“搜索用户”按钮,它会返回该用户最近 15 条左右的推文。
我相信我已经完成了第一部分,但是在弄清楚如何从特定用户那里调出推文时有点卡住了。非常感谢任何进一步的指导。
package twitter;
import java.awt.Button;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.List;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Tweet;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.TwitterStream;
public class SearchListener extends KeyAdapter implements ActionListener {
private Button searchButton;
private Button searchUserButton;
private TextField searchText;
private TextArea results;
private Twitter twitter;
public SearchListener(Button searchButton, Button searchUserButton,
TextField searchText, TextArea results) {
this.searchButton = searchButton;
this.searchUserButton = searchUserButton;
this.searchText = searchText;
this.results = results;
results.setText("(ready for search)");
twitter = (new TwitterFactory()).getInstance();
}
@Override
public void actionPerformed(ActionEvent e) {
doSearch();
}
private void doSearch() {
String searchStr = searchText.getText();
results.setText("searching for: " + searchStr + "\n");
if (searchStr == null || searchStr.length() == 0) {
return;
}
try {
QueryResult result = twitter.search(new Query(searchStr));
List<Tweet> tweets = result.getTweets();
int i = 0;
for (Tweet tweet : tweets) {
results.append("" + i + ": ");
results.append("@" + tweet.getFromUser() + " - "
+ tweet.getText());
results.append("\n\n");
i++;
}
results.append("" + i + " total tweets found\n");
} catch (TwitterException te) {
te.printStackTrace();
results.append("Failed to search tweets: " + te.getMessage());
System.exit(-1);
}
}
@Override
public void keyTyped(KeyEvent e) {
// results.append(e.getKeyChar() + "\n");
if (e.getKeyChar() == '\n') {
doSearch();
}
}
}