简体   繁体   中英

Twitter4j : Search

I use Twitter4j to get status with hashtag :

ConfigurationBuilder cb = new ConfigurationBuilder();
            cb.setDebugEnabled(true)
              .setOAuthConsumerKey("*******")
              .setOAuthConsumerSecret("****")
              .setOAuthAccessToken("*****")
              .setOAuthAccessTokenSecret("*****");
            TwitterFactory tf = new TwitterFactory(cb.build());
            Twitter twitter = tf.getInstance();
            Query query = new Query("source:twitter4j yusukey");
            QueryResult result;
            try {
                result = twitter.search(query);
                for (Status status : result.getTweets()) {
                    System.out.println("@" + status.getUser().getScreenName() + ":" + status.getText());
                }
            } catch (TwitterException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

I replaced the * with keys , But the application is unable to start

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.app_evnt/com.example.app_evnt.SocialNetwork}: android.os.NetworkOnMainThreadException

all networkcalls are not allowed on main thread, you can try it like this to do it in another thread:

ConfigurationBuilder cb = new ConfigurationBuilder();
            cb.setDebugEnabled(true)
              .setOAuthConsumerKey("*******")
              .setOAuthConsumerSecret("****")
              .setOAuthAccessToken("*****")
              .setOAuthAccessTokenSecret("*****");
            TwitterFactory tf = new TwitterFactory(cb.build());
            final Twitter twitter = tf.getInstance();
            Query query = new Query("source:twitter4j yusukey");

            new Thread(new Runnable() { 
                @Override
                public void run() {
                    try {
                        QueryResult result = twitter.search(query);
                        for (Status status : result.getTweets()) {
                                System.out.println("@" + status.getUser().getScreenName() + ":" + status.getText());
                        }
                    } catch (TwitterException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            }).start();

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