Android - 如何从Twitter API获取某人的推文

时间:2017-08-26 19:10:39

标签: android twitter

我用谷歌搜索来自Twitter API (JSON Object).

的人的推文

但我没有得到任何完美的解决方案。

我尝试使用QueryResult,但显示# HASH_TAG@ Tag

有没有办法获取某人的推文(I have the User ID and Screen Name).

这是我尝试过的代码:

ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);

User user;
AccessToken accessToken = new AccessToken(TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_TOKEN_SECRET);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);

List<twitter4j.Status> statusList = new ArrayList<>();
Query query = new Query("%23tarak9999");
query.setCount(20);

QueryResult result = twitter.search(query);
statusList = result.getTweets();

谢谢

2 个答案:

答案 0 :(得分:1)

以下是设置UserTimeline的示例:

import com.twitter.sdk.android.tweetui.TweetTimelineListAdapter;
import com.twitter.sdk.android.tweetui.UserTimeline;
public class TimelineActivity extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.timeline);
TwitterConfig config = new TwitterConfig.Builder(this)
        .twitterAuthConfig(new
TwitterAuthConfig(TWITTER_CONSUMER_KEY, 
TWITTER_CONSUMER_SECRET)).build();
Twitter.initialize(config);
final UserTimeline userTimeline = new UserTimeline.Builder()
        .screenName("twitterdev")
        .build();
final TweetTimelineListAdapter adapter = new TweetTimelineListAdapter.Builder(this)
        .setTimeline(userTimeline)
        .build();
setListAdapter(adapter);
 }
}

和相应的XML布局timeline.xml,为清晰起见显示没有资源引用的属性值:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="@id/android:empty"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:gravity="center_horizontal|center_vertical"
          android:text="No Tweets"/>
<ListView android:id="@id/android:list"
          android:layout_width="match_parent"
          android:layout_height="0dp"
          android:layout_weight="1"
          android:divider="#e1e8ed"
          android:dividerHeight="1dp"
          android:drawSelectorOnTop="false"/
</LinearLayout>

答案 1 :(得分:1)

Malik Ahsan上面提到的答案正在抛出错误

RunTimeError: Must initialize Twitter before using getInstance()

添加以下行解决了这个问题:

TwitterConfig config = new TwitterConfig.Builder(this)
            .twitterAuthConfig(new TwitterAuthConfig(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET)).build();
Twitter.initialize(config);

上面添加的行

UserTimeline userTimeline = new UserTimeline.Builder().screenName("SCREEN_NAME").build();