Search code examples
androidtwitterwebviewtwitter4j

Consuming and Filtering Tweets using Twitter4j-4.0.2


I am trying to get Tweets based on user input string and parse tweet text, extract web link from the tweet (ignore tweets without a web link) and parse it to show in WebView Dialog with a next button(so when clicked to move to the next WebView(show next content of the link parsed from tweet)). I am getting the tweets result (without filtering), how can i filter them and get the URL so i can parse it for the WebView ?

Here is the code i am running on background thread:

 @Override
            protected WebView doInBackground(String... strings) {
                //Get userInput
                String searchTerm = strings[0];
                //Initialize Twitter Connection
                ConfigurationBuilder builder = new ConfigurationBuilder();
                    builder.setDebugEnabled(true);
                    builder.setOAuthConsumerKey(sharedPreferences.getString(TwitterConstants.getPrefConsumerKey(), ""));
                    builder.setOAuthConsumerSecret(sharedPreferences.getString(TwitterConstants.getPrefConsumerSecret(), ""));
                AccessToken accessToken = new AccessToken(sharedPreferences.getString(TwitterConstants.getPrefAccessToken(), ""), sharedPreferences.getString(TwitterConstants.getPrefAccessTokenSecret(), ""));
                Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
                try {
                    //Query object
                    Query query = new Query(searchTerm);
                    //The number of tweets to return per page [max:100]
                    query.count(2);
                    //Return only the most recent results in the response
                    query.resultType(Query.ResultType.recent);
                    QueryResult result = twitter.search(query);
                    Log.e("Twitter QueryResult", result.toString());
                }catch(TwitterException e){
                    e.printStackTrace();
                }
                return null;
            }

Solution

  • If you are using twitter4j Library, there is URLEntity class which you can get from twitter4j.Status by calling status.getURLEntities();This will return an Array of URLEntity. So here you go, you can check if the tweet has urlEntity inside and you can get the url mentioned in the tweet by calling urlEntity.getURL();

    EDIT For the answer including code, take a look @hrskrs 's answer below.