0

我使用 Twitter4j 来获取带有标签的状态:

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();
            }

我用键替换*,但应用程序无法启动

java.lang.RuntimeException:无法启动活动 ComponentInfo{com.example.app_evnt/com.example.app_evnt.SocialNetwork}:android.os.NetworkOnMainThreadException

4

1 回答 1

0

主线程上不允许所有网络调用,您可以像这样在另一个线程中尝试这样做:

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();
于 2013-07-31T12:08:13.873 回答