Example usage for twitter4j Query Query

List of usage examples for twitter4j Query Query

Introduction

In this page you can find the example usage for twitter4j Query Query.

Prototype

public Query(String query) 

Source Link

Usage

From source file:com.javielinux.database.EntitySearch.java

License:Apache License

public Query getQuery(Context cnt) {
    String q = this.getString("words_and");

    if (!this.getString("words_or").equals("")) {
        q += Utils.getQuotedText(this.getString("words_or"), "OR ", false);
    }/* w w  w .j  a v  a  2 s.  c om*/

    if (!this.getString("words_not").equals("")) {
        q += Utils.getQuotedText(this.getString("words_not"), "-", true);
    }

    if (!this.getString("from_user").equals("")) {
        q += " from:" + this.getString("from_user");
    }

    if (!this.getString("to_user").equals("")) {
        q += " to:" + this.getString("to_user");
    }

    if (!this.getString("source").equals("")) {
        q += " source:" + this.getString("source");
    }

    if (this.getInt("attitude") == 1)
        q += " :)";
    if (this.getInt("attitude") == 2)
        q += " :(";

    String modLinks = "filter:links";
    String websVideos = "twitvid OR youtube OR vimeo OR youtu.be";
    String webPhotos = "lightbox.com OR mytubo.net OR imgur.com OR instagr.am OR twitpic OR yfrog OR plixi OR twitgoo OR img.ly OR picplz OR lockerz";

    if (this.getInt("filter") == 1)
        q += " " + modLinks;
    if (this.getInt("filter") == 2)
        q += " " + webPhotos + " " + modLinks;
    if (this.getInt("filter") == 3)
        q += " " + websVideos + " " + modLinks;
    if (this.getInt("filter") == 4)
        q += " " + websVideos + " OR " + webPhotos + " " + modLinks;
    if (this.getInt("filter") == 5)
        q += " source:twitterfeed " + modLinks;
    if (this.getInt("filter") == 6)
        q += " ?";
    if (this.getInt("filter") == 7)
        q += " market.android.com OR androidzoom.com OR androlib.com OR appbrain.com OR bubiloop.com OR yaam.mobi OR slideme.org "
                + modLinks;

    Log.d(Utils.TAG, "Buscando: " + q);

    Query query = new Query(q);

    if (this.getInt("use_geo") == 1) {
        if (this.getInt("type_geo") == 0) { // coordenadas del mapa
            GeoLocation gl = new GeoLocation(this.getDouble("latitude"), this.getDouble("longitude"));
            String unit = Query.KILOMETERS;
            if (this.getInt("type_distance") == 0)
                unit = Query.MILES;
            query.setGeoCode(gl, this.getDouble("distance"), unit);
        }

        if (this.getInt("type_geo") == 1) { // coordenadas del gps
            Location loc = LocationUtils.getLastLocation(cnt);
            if (loc != null) {
                GeoLocation gl = new GeoLocation(loc.getLatitude(), loc.getLongitude());
                String unit = Query.KILOMETERS;
                if (this.getInt("type_distance") == 0)
                    unit = Query.MILES;
                query.setGeoCode(gl, this.getDouble("distance"), unit);
            } else {
                mErrorLastQuery = cnt.getString(R.string.no_location);
            }
        }
    }

    PreferenceManager.setDefaultValues(cnt, R.xml.preferences, false);
    SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(cnt);

    int count = Integer.parseInt(preference.getString("prf_n_max_download", "60"));
    if (count <= 0)
        count = 60;

    query.setCount(count);

    String lang = "";
    if (!this.getString("lang").equals(""))
        lang = this.getString("lang");
    if (!lang.equals("all"))
        query.setLang(lang);

    // obtener desde donde quiero hacer la consulta

    if (getInt("notifications") == 1) {
        String where = "search_id = " + this.getId() + " AND favorite = 0";
        int nResult = DataFramework.getInstance().getEntityListCount("tweets", where);
        if (nResult > 0) {
            long mLastIdNotification = DataFramework.getInstance().getTopEntity("tweets", where, "date desc")
                    .getLong("tweet_id");
            query.setSinceId(mLastIdNotification);
        }
    }

    //query.setResultType(Query.POPULAR);

    return query;
}

From source file:com.klinker.android.twitter.activities.drawer_activities.discover.trends.SearchedTrendsActivity.java

License:Apache License

public void onRefreshStarted() {
    new Thread(new Runnable() {
        @Override/* w w  w.  j a  v  a 2s  .c  o  m*/
        public void run() {

            final long topId;
            if (tweets.size() > 0) {
                topId = tweets.get(0).getId();
            } else {
                topId = 0;
            }

            try {
                Twitter twitter = Utils.getTwitter(context, settings);
                query = new Query(searchQuery);
                QueryResult result = twitter.search(query);

                tweets.clear();

                for (twitter4j.Status status : result.getTweets()) {
                    tweets.add(status);
                }

                if (result.hasNext()) {
                    query = result.nextQuery();
                    hasMore = true;
                } else {
                    hasMore = false;
                }

                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        int top = 0;
                        for (int i = 0; i < tweets.size(); i++) {
                            if (tweets.get(i).getId() == topId) {
                                top = i;
                                break;
                            }
                        }

                        adapter = new TimelineArrayAdapter(context, tweets);
                        listView.setAdapter(adapter);
                        listView.setVisibility(View.VISIBLE);
                        listView.setSelection(top);

                        spinner.setVisibility(View.GONE);

                        mPullToRefreshLayout.setRefreshing(false);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        spinner.setVisibility(View.GONE);
                        mPullToRefreshLayout.setRefreshing(false);
                    }
                });
            }
        }
    }).start();
}

From source file:com.klinker.android.twitter.activities.search.TwitterSearchFragment.java

License:Apache License

public void doSearch(final String mQuery) {
    spinner.setVisibility(View.VISIBLE);

    if (listView.getVisibility() != View.GONE) {
        listView.setVisibility(View.GONE);
    }/* ww w.j  a va2  s.  c o m*/

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Twitter twitter = Utils.getTwitter(context, settings);
                Log.v("talon_searching", "query in frag: " + mQuery);
                query = new Query(mQuery);
                if (topTweets) {
                    query.setResultType(Query.ResultType.popular);
                } else {
                    query.setResultType(null);
                }
                QueryResult result = twitter.search(query);

                tweets.clear();

                for (twitter4j.Status status : result.getTweets()) {
                    tweets.add(status);
                }

                if (result.hasNext()) {
                    query = result.nextQuery();
                    hasMore = true;
                } else {
                    hasMore = false;
                }

                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter = new TimelineArrayAdapter(context, tweets, onlyStatus);
                        listView.setAdapter(adapter);
                        listView.setVisibility(View.VISIBLE);

                        spinner.setVisibility(View.GONE);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        spinner.setVisibility(View.GONE);
                    }
                });
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        spinner.setVisibility(View.GONE);
                    }
                });
            }
        }
    }).start();
}

From source file:com.klinker.android.twitter.activities.tweet_viewer.fragments.ConversationFragment.java

License:Apache License

public void getDiscussion(final ListView listView, final long tweetId, final LinearLayout progressBar,
        final HoloTextView none, final Status status) {

    Log.v("talon_replies", "getting discussion");

    if (replies.size() == 0) {
        replies.add(status);//from w  ww. j  a  v  a2  s  .c o m
    }

    Thread getReplies = new Thread(new Runnable() {
        @Override
        public void run() {

            if (!isRunning) {
                return;
            }

            ArrayList<twitter4j.Status> all = null;
            Twitter twitter = Utils.getTwitter(context, settings);
            try {
                Log.v("talon_replies", "looking for discussion");

                long id = status.getId();
                String screenname = status.getUser().getScreenName();

                query = new Query("@" + screenname + " since_id:" + id);

                Log.v("talon_replies", "query string: " + query.getQuery());

                try {
                    query.setCount(100);
                } catch (Throwable e) {
                    // enlarge buffer error?
                    query.setCount(30);
                }

                QueryResult result = twitter.search(query);
                Log.v("talon_replies", "result: " + result.getTweets().size());

                all = new ArrayList<twitter4j.Status>();

                do {
                    Log.v("talon_replies", "do loop repetition");
                    if (!isRunning) {
                        return;
                    }
                    List<Status> tweets = result.getTweets();

                    for (twitter4j.Status tweet : tweets) {
                        if (tweet.getInReplyToStatusId() == id) {
                            all.add(tweet);
                            Log.v("talon_replies", tweet.getText());
                        }
                    }

                    if (all.size() > 0) {
                        for (int i = all.size() - 1; i >= 0; i--) {
                            Log.v("talon_replies", "inserting into arraylist:" + all.get(i).getText());
                            replies.add(all.get(i));
                        }

                        all.clear();

                        ((Activity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                progressBar.setVisibility(View.GONE);
                                try {
                                    if (replies.size() > 0) {
                                        if (adapter == null || adapter.getCount() == 0) {
                                            adapter = new TimelineArrayAdapter(context, replies);
                                            listView.setAdapter(adapter);
                                            listView.setVisibility(View.VISIBLE);
                                        } else {
                                            Log.v("talon_replies", "notifying adapter change");
                                            adapter.notifyDataSetChanged();
                                        }
                                    } else {
                                        none.setVisibility(View.VISIBLE);
                                    }
                                } catch (Exception e) {
                                    // none and it got the null object
                                    e.printStackTrace();
                                    listView.setVisibility(View.GONE);
                                    none.setVisibility(View.VISIBLE);
                                }
                            }
                        });
                    }

                    try {
                        Thread.sleep(250);
                    } catch (Exception e) {
                        // since we are changing the arraylist for the adapter in the background, we need to make sure it
                        // gets updated before continuing
                    }

                    query = result.nextQuery();

                    if (query != null)
                        result = twitter.search(query);

                } while (query != null);

            } catch (Exception e) {
                e.printStackTrace();
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
            }

            if (replies.size() < 2) {
                // nothing to show, so tell them that
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progressBar.setVisibility(View.GONE);
                        listView.setVisibility(View.GONE);
                        none.setVisibility(View.VISIBLE);
                    }
                });
            }
        }
    });

    getReplies.setPriority(8);
    getReplies.start();

}

From source file:com.lbarriosh.sentimentanalyzer.downloads.TweetsDownloader.java

License:Open Source License

public List<Status> downloadTweets(String[] keywords, TwitterLocale locale, int max_results)
        throws TwitterException {
    Twitter twitter = this.tf.getInstance();
    Query query = new Query(buildQuery(keywords));
    QueryResult result;/*w w w.  j a va2 s.com*/
    ArrayList<Status> retrieved_tweets = new ArrayList<Status>();
    do {
        result = twitter.search(query);
        for (Status tweet : result.getTweets()) {
            if (tweet.getLang().equals(locale.toString())) {
                retrieved_tweets.add(tweet); // Workaround. There's a bug in
                // Twitter4j.
            }
            if (retrieved_tweets.size() == max_results)
                break;
        }
    } while ((query = result.nextQuery()) != null && retrieved_tweets.size() < max_results);
    return retrieved_tweets;
}

From source file:com.learnncode.twitter.async.HashtagTweetFetchAsyncTask.java

License:Apache License

@Override
protected List<twitter4j.Status> doInBackground(Object... params) {

    List<twitter4j.Status> list = new ArrayList<twitter4j.Status>();
    if (AppUtilities.IsNetworkAvailable(mContext)) {

        try {//from   www .j ava2s  . co m
            Twitter twitter;
            if (AppSettings.isTwitterAuthenticationDone(mContext)) {
                twitter = TwitterHelper.getTwitterInstance(mContext);

            } else {
                twitter = TwitterHelper.getTwitterInstanceWithoutAuthentication(mContext);
            }
            Query query = new Query(hashtag);
            query.count(10);
            if (lastSeenId != 0) {
                query.setMaxId(lastSeenId);
            }
            QueryResult qr = twitter.search(query);
            List<twitter4j.Status> qrTweets = qr.getTweets();

            for (twitter4j.Status t : qrTweets) {
                list.add(t);
            }

        } catch (Exception e) {
            System.err.println();
        }
    }
    if (lastSeenId != 0) {
        iHashTagList.setTweetList(list, true);
    } else {
        iHashTagList.setTweetList(list, false);
    }

    return list;
}

From source file:com.mothsoft.integration.twitter.TwitterServiceImpl.java

License:Apache License

public List<Status> search(final String query) {
    try {//from   www . j a v  a 2s . c  o m
        final Twitter twitter = factory.getInstance();
        final QueryResult queryResult = twitter.search(new Query(query));
        final List<Status> tweets = queryResult.getTweets();
        return tweets;
    } catch (TwitterException e) {
        throw wrapException(e);
    }
}

From source file:com.mycompany.dovetune.SearchTwitter.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* ww  w .  j a v  a2 s  .c  o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, TwitterException {

    //            HttpSession session = request.getSession(false);

    //            if(session != null){

    Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");

    if (twitter != null) {
        String soundcloudUrl = request.getParameter("soundcloudUrl");
        String songName = request.getParameter("songName");
        out.println(twitter.toString());

        int i = songName.indexOf("- ");
        String song = songName.substring(i + 2);
        try {
            Query query = new Query("(#" + song + ") OR ( " + songName + ") OR (#DoveTune)");

            QueryResult result = twitter.search(query);

            List<Status> tweets = result.getTweets();
            //                String list = "<ulid='tweetList'>";
            String list = "";
            for (Status tweet : tweets) {
                list += "<li><img class='profileImg' src='" + tweet.getUser().getProfileImageURL()
                        + "' title='Profile Image' alt='Profile Image'><strong>" + tweet.getUser().getName()
                        + " @" + tweet.getUser().getScreenName() + "</strong> - " + tweet.getText() + "</li>";
            }

            list = list.replace("#" + song, "<strong class='hashtags'>#" + song + "</strong>");
            list = list.replace("#DoveTune", "<strong class='hashtags'>#DoveTune</strong>");
            list = list.replace("#SoundCloud", "<strong class='hashtags'>#SoundCloud</strong>");
            String songL = song;
            songL = songL.toLowerCase();
            list = list.replace("#" + songL, "<strong class='hashtags'>#" + songL + "</strong>");
            if (list.equals("")) {
                list = "<li>There are no tweets to display. Tweet your own!</li>";
            }

            request.setAttribute("soundcloudUrl", soundcloudUrl);
            request.setAttribute("songName", songName);
            request.setAttribute("song", songName);
            request.setAttribute("list", list);

        } catch (TwitterException te) {
            te.printStackTrace();
            out.println("Failed to search tweets: " + te.getMessage());
            System.exit(-1);
        }
    } else {
        String list = "<ul><li>In order to view tweets, please sign in to <a href=\"SignIn\" title=\"Sign in to Twitter\"><strong class=\"notSignedIn\">Twitter</strong></a></li></ul>";
        request.setAttribute("list", list);
    }

    request.getRequestDispatcher("details.jsp").forward(request, response);

}

From source file:com.mycompany.omnomtweets.TweetsAboutCandidates.java

/**
 * Searches for tweets using the given query string.
 * @param str the query to use/*from   ww  w .  j av  a  2  s. c  om*/
 * @return List of the tweet statuses that match the query.
 */
public List<Status> search(String str, long maxId) {
    List<Status> tweets = null;
    try {
        Query query = new Query(str);
        query.setCount(100);
        //English only.
        query.setLang("en");
        QueryResult result;
        query.setMaxId(maxId);
        result = twitter.search(query);
        tweets = result.getTweets();
    } catch (TwitterException te) {
        System.out.println("Failed to search tweets: " + te.getMessage());
    }
    return tweets;
}

From source file:com.mycompany.twitterapp.TwitterApp.java

public void getTweet() {

    Query query = new Query(tweetSearchWord);
    QueryResult result = null;/*from   w  w w .  j  a  va2  s  .c o m*/
    try {
        result = twitter.search(query);
    } catch (TwitterException ex) {
        java.util.logging.Logger.getLogger(TwitterApp.class.getName()).log(Level.SEVERE, null, ex);
    }
    if (result == null) {
        System.out.println("nope");
        return;
    }
    for (Status status : result.getTweets()) {
        System.out.println("@" + status.getUser().getScreenName() + ":" + status.getText());
    }
}