Example usage for twitter4j QueryResult getTweets

List of usage examples for twitter4j QueryResult getTweets

Introduction

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

Prototype

List<Status> getTweets();

Source Link

Usage

From source file:com.javielinux.api.loaders.UserMentionsLoader.java

License:Apache License

@Override
public BaseResponse loadInBackground() {

    try {/*from  www  .  j ava  2 s.  co m*/
        UserMentionsResponse response = new UserMentionsResponse();

        ArrayList<InfoTweet> infoTweets = new ArrayList<InfoTweet>();

        String query_text = " to:" + this.request.getInfoUsers().getName();
        Query query = new Query(query_text);
        QueryResult result = ConnectionManager.getInstance().getUserForSearchesTwitter().search(query);

        ArrayList<Status> tweets = (ArrayList<Status>) result.getTweets();
        for (Status tweet : tweets) {
            infoTweets.add(new InfoTweet(tweet));
        }

        response.setInfoTweets(infoTweets);

        return response;
    } catch (Exception e) {
        e.printStackTrace();
        ErrorResponse response = new ErrorResponse();
        response.setError(e, e.getMessage());
        return response;
    }
}

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

License:Apache License

public InfoSaveTweets saveTweets(Context cnt, boolean saveNotifications, long since_id) {
    ConnectionManager.getInstance().open(cnt);
    Twitter twitter = ConnectionManager.getInstance().getUserForSearchesTwitter();
    InfoSaveTweets out = new InfoSaveTweets();
    try {// w  w  w.  ja  v  a 2  s. c  o  m
        int nResult = DataFramework.getInstance().getEntityListCount("tweets",
                "favorite=0 and search_id=" + getId());

        Query query = getQuery(cnt);
        if (since_id != -1)
            query.setSinceId(since_id);

        QueryResult result = twitter.search(query);
        ArrayList<Status> tweets = (ArrayList<Status>) result.getTweets();

        if (tweets.size() > 0) {

            out.setNewMessages(tweets.size());
            out.setNewerId(tweets.get(0).getId());
            out.setOlderId(tweets.get(tweets.size() - 1).getId());
            if (saveNotifications) {
                setValue("new_tweets_count", getInt("new_tweets_count") + tweets.size());
                save();
            }

            Log.d(Utils.TAG, tweets.size() + " mensajes nuevos en " + getString("name"));

            long fisrtId = 1;
            Cursor c = DataFramework.getInstance().getCursor("tweets", new String[] { DataFramework.KEY_ID },
                    null, null, null, null, DataFramework.KEY_ID + " desc", "1");
            if (!c.moveToFirst()) {
                c.close();
                fisrtId = 1;
            } else {
                long Id = c.getInt(0) + 1;
                c.close();
                fisrtId = Id;
            }

            for (int i = tweets.size() - 1; i >= 0; i--) {

                /*String sql = "INSERT INTO 'tweets' ("  + DataFramework.KEY_ID + ", search_id, url_avatar, username, user_id, tweet_id,"
                      + "text, source, to_username, to_user_id, date, favorite) VALUES (" + fisrtId + "," + getId()
                      + ",'" +tweets.get(i).getProfileImageUrl() + "','"+tweets.get(i).getFromUser()+"','"
                      + tweets.get(i).getFromUserId() + "','" + tweets.get(i).getId() + "','" + tweets.get(i).getText() 
                      + "','" + tweets.get(i).getSource()   + "','"+tweets.get(i).getToUser()
                      +"','"+tweets.get(i).getToUserId()+"','"+String.valueOf(tweets.get(i).getCreatedAt().getTime())
                      + "',0);\n";*/
                User u = tweets.get(i).getUser();
                ContentValues args = new ContentValues();
                args.put(DataFramework.KEY_ID, "" + fisrtId);
                args.put("search_id", "" + getId());
                if (u.getProfileImageURL() != null) {
                    args.put("url_avatar", u.getProfileImageURL().toString());
                } else {
                    args.put("url_avatar", "");
                }
                args.put("username", u.getScreenName());
                args.put("fullname", u.getName());
                args.put("user_id", "" + u.getId());
                args.put("tweet_id", Utils.fillZeros("" + tweets.get(i).getId()));
                args.put("text", tweets.get(i).getText());
                args.put("source", tweets.get(i).getSource());
                args.put("to_username", tweets.get(i).getInReplyToScreenName());
                args.put("to_user_id", "" + tweets.get(i).getInReplyToUserId());
                args.put("date", String.valueOf(tweets.get(i).getCreatedAt().getTime()));
                if (tweets.get(i).getGeoLocation() != null) {
                    args.put("latitude", tweets.get(i).getGeoLocation().getLatitude());
                    args.put("longitude", tweets.get(i).getGeoLocation().getLongitude());
                }
                args.put("favorite", "0");

                DataFramework.getInstance().getDB().insert("tweets", null, args);

                fisrtId++;

            }

            if (saveNotifications) {
                setValue("last_tweet_id_notifications", tweets.get(0).getId() + "");
                save();
            }

            int total = nResult + tweets.size();
            if (total > Utils.MAX_ROW_BYSEARCH) {
                Log.d(Utils.TAG, "Limpiando base de datos");
                String date = DataFramework.getInstance()
                        .getEntityList("tweets", "favorite=0 and search_id=" + getId(), "date desc")
                        .get(Utils.MAX_ROW_BYSEARCH).getString("date");
                String sqldelete = "DELETE FROM tweets WHERE favorite=0 AND search_id=" + getId()
                        + " AND date  < '" + date + "'";
                DataFramework.getInstance().getDB().execSQL(sqldelete);
            }

        }

    } catch (TwitterException e) {
        e.printStackTrace();
        RateLimitStatus rate = e.getRateLimitStatus();
        if (rate != null) {
            out.setError(Utils.LIMIT_ERROR);
            out.setRate(rate);
        } else {
            out.setError(Utils.UNKNOWN_ERROR);
        }
    } catch (Exception e) {
        e.printStackTrace();
        out.setError(Utils.UNKNOWN_ERROR);
    }
    return out;
}

From source file:com.javielinux.widget.ServiceWidgetTweets4x2.java

License:Apache License

public void update(Context context) {

    blocked = true;//from   w  w  w. ja  v  a 2 s  . com

    mCurrentTweet = 0;

    RemoteViews mRemoteLoading = new RemoteViews(context.getPackageName(), R.layout.widget_loading);
    getManager().updateAppWidget(getWidget(), mRemoteLoading);

    mTweets.clear();
    clearImagesTweets();

    mType = PreferenceUtils.getTypeWidget(context);
    mCurrentSearch = PreferenceUtils.getIdSearchWidget(context);
    long column_id = PreferenceUtils.getWidgetColumn(context);

    try {
        column = new Entity("columns", column_id);
    } catch (CursorIndexOutOfBoundsException e) {
    } catch (Exception e) {
    }

    if (column != null) {

        ArrayList<Entity> tweetList = new ArrayList<Entity>();

        switch (column.getInt("type_id")) {
        case TweetTopicsUtils.COLUMN_TIMELINE:
            //loadUser(columns.get(0).getEntity("user_id").getId());
            tweetList
                    .addAll(DataFramework.getInstance().getEntityList(
                            "tweets_user", "type_id=" + TweetTopicsUtils.TWEET_TYPE_TIMELINE
                                    + " and user_tt_id=" + column.getEntity("user_id").getId(),
                            "date desc", "0,10"));

            for (int i = 0; i < tweetList.size(); i++) {
                mTweets.add(new InfoTweet(tweetList.get(i)));
            }
            break;
        case TweetTopicsUtils.COLUMN_MENTIONS:
            //loadUser(columns.get(0).getEntity("user_id").getId());
            tweetList
                    .addAll(DataFramework.getInstance().getEntityList(
                            "tweets_user", "type_id=" + TweetTopicsUtils.TWEET_TYPE_MENTIONS
                                    + " and user_tt_id=" + column.getEntity("user_id").getId(),
                            "date desc", "0,10"));

            for (int i = 0; i < tweetList.size(); i++) {
                mTweets.add(new InfoTweet(tweetList.get(i)));
            }
            break;
        case TweetTopicsUtils.COLUMN_DIRECT_MESSAGES:
            //loadUser(columns.get(0).getEntity("user_id").getId());
            tweetList
                    .addAll(DataFramework.getInstance().getEntityList(
                            "tweets_user", "type_id=" + TweetTopicsUtils.TWEET_TYPE_DIRECTMESSAGES
                                    + " and user_tt_id=" + column.getEntity("user_id").getId(),
                            "date desc", "0,10"));

            for (int i = 0; i < tweetList.size(); i++) {
                mTweets.add(new InfoTweet(tweetList.get(i)));
            }
            break;
        case TweetTopicsUtils.COLUMN_SEARCH:
            try {
                EntitySearch entitySearch = new EntitySearch(column.getLong("search_id"));
                QueryResult result = twitter.search(entitySearch.getQuery(context));
                ArrayList<Status> tweets = (ArrayList<Status>) result.getTweets();

                for (int i = 0; i < 10; i++) {
                    mTweets.add(new InfoTweet(tweets.get(i)));
                }
            } catch (TwitterException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            break;
        //                case TweetTopicsUtils.COLUMN_RETWEETS_BY_OTHERS:
        //                    // TODO retweet
        //                    try {
        //                        ResponseList<Status> statii = ConnectionManager.getInstance().getTwitter(column.getEntity("user_id").getId()).getRetweetsOfMe();
        //
        //                        for (int i=0; i<statii.size(); i++) {
        //                            mTweets.add(new InfoTweet(statii.get(i)));
        //                        }
        //                    } catch (TwitterException e) {
        //                        e.printStackTrace();
        //                    } catch (Exception e) {
        //                        e.printStackTrace();
        //                    }
        //                    break;
        //                case TweetTopicsUtils.COLUMN_RETWEETS_BY_YOU:
        //                    // TODO retweet
        ////                    try {
        ////                        ResponseList<Status> statii = ConnectionManager.getInstance().getTwitter(column.getEntity("user_id").getId()).getRetweetedByMe();
        ////
        ////                        for (int i=0; i<statii.size(); i++) {
        ////                            mTweets.add(new InfoTweet(statii.get(i)));
        ////                        }
        ////                    } catch (TwitterException e) {
        ////                        e.printStackTrace();
        ////                    } catch (Exception e) {
        ////                        e.printStackTrace();
        ////                    }
        //                    break;
        //                case TweetTopicsUtils.COLUMN_FAVORITES:
        //                    try {
        //                        ResponseList<Status> statii = ConnectionManager.getInstance().getTwitter(column.getEntity("user_id").getId()).getFavorites();
        //
        //                        for (int i=0; i<statii.size(); i++) {
        //                            mTweets.add(new InfoTweet(statii.get(i)));
        //                        }
        //                    } catch (TwitterException e) {
        //                        e.printStackTrace();
        //                    } catch (Exception e) {
        //                        e.printStackTrace();
        //                    }
        //                    break;
        //                case TweetTopicsUtils.COLUMN_FOLLOWERS:
        //                    try {
        //                        IDs followers_ids = ConnectionManager.getInstance().getTwitter(column.getEntity("user_id").getId()).getFollowersIDs(column.getEntity("user_id").getString("name"), -1);
        //
        //                        ResponseList<User> users = null;
        //
        //                        if (followers_ids.getIDs().length <= 100) {
        //                            users = ConnectionManager.getInstance().getTwitter(column.getEntity("user_id").getId()).lookupUsers(followers_ids.getIDs());
        //                        } else {
        //                            int hundred_count = followers_ids.getIDs().length / 100;
        //
        //                            for (int i=0; i < hundred_count; i++) {
        //                                if (users == null)
        //                                    users = ConnectionManager.getInstance().getTwitter(column.getEntity("user_id").getId()).lookupUsers(Arrays.copyOfRange(followers_ids.getIDs(), i * 100, (i + 1) * 100 - 1));
        //                                else
        //                                    users.addAll(ConnectionManager.getInstance().getTwitter(column.getEntity("user_id").getId()).lookupUsers(Arrays.copyOfRange(followers_ids.getIDs(),i*100,(i+1)*100-1)));
        //                            }
        //
        //                            if (followers_ids.getIDs().length % 100 > 0)
        //                                users.addAll(ConnectionManager.getInstance().getTwitter(column.getEntity("user_id").getId()).lookupUsers(Arrays.copyOfRange(followers_ids.getIDs(),hundred_count*100 + 1,followers_ids.getIDs().length-1)));
        //                        }
        //
        //                        for (User user : users) {
        //                            InfoTweet row = new InfoTweet(user);
        //                            mTweets.add(row);
        //                        }
        //                    } catch (TwitterException e) {
        //                        e.printStackTrace();
        //                    } catch (Exception e) {
        //                        e.printStackTrace();
        //                    }
        //                    break;
        //                case TweetTopicsUtils.COLUMN_FOLLOWINGS:
        //                    try {
        //                        IDs friends_ids = ConnectionManager.getInstance().getTwitter(column.getEntity("user_id").getId()).getFriendsIDs(column.getEntity("user_id").getString("name"), -1);
        //
        //                        ResponseList<User> users = null;
        //
        //                        if (friends_ids.getIDs().length <= 100) {
        //                            users = ConnectionManager.getInstance().getTwitter(column.getEntity("user_id").getId()).lookupUsers(friends_ids.getIDs());
        //                        } else {
        //                            int hundred_count = friends_ids.getIDs().length / 100;
        //
        //                            for (int i=0; i < hundred_count; i++) {
        //                                if (users == null)
        //                                    users = ConnectionManager.getInstance().getTwitter(column.getEntity("user_id").getId()).lookupUsers(Arrays.copyOfRange(friends_ids.getIDs(), i * 100, (i + 1) * 100 - 1));
        //                                else
        //                                    users.addAll(ConnectionManager.getInstance().getTwitter(column.getEntity("user_id").getId()).lookupUsers(Arrays.copyOfRange(friends_ids.getIDs(),i*100,(i+1)*100-1)));
        //                            }
        //
        //                            if (friends_ids.getIDs().length % 100 > 0)
        //                                users.addAll(ConnectionManager.getInstance().getTwitter(column.getEntity("user_id").getId()).lookupUsers(Arrays.copyOfRange(friends_ids.getIDs(),hundred_count*100 + 1,friends_ids.getIDs().length-1)));
        //                        }
        //
        //                        for (User user : users) {
        //                            InfoTweet row = new InfoTweet(user);
        //                            mTweets.add(row);
        //                        }
        //                    } catch (TwitterException e) {
        //                        e.printStackTrace();
        //                    } catch (Exception e) {
        //                        e.printStackTrace();
        //                    }
        //                    break;
        case TweetTopicsUtils.COLUMN_LIST_USER:
            try {
                Entity user_list_entity = new Entity("user_lists",
                        Long.parseLong(column.getValue("userlist_id").toString()));

                ResponseList<twitter4j.Status> statii = ConnectionManager.getInstance()
                        .getTwitter(user_list_entity.getLong("user_id"))
                        .getUserListStatuses(user_list_entity.getInt("userlist_id"), new Paging(1));
                for (int i = 0; i < 10; i++) {
                    mTweets.add(new InfoTweet(statii.get(i)));
                }
            } catch (TwitterException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    blocked = false;

}

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//from   w  ww .ja  v a 2  s .  c om
        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.drawer_activities.discover.trends.SearchedTrendsActivity.java

License:Apache License

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

    new Thread(new Runnable() {
        @Override//from ww w.j a  v  a  2 s .  c  o  m
        public void run() {
            try {
                Twitter twitter = Utils.getTwitter(context, settings);

                Log.v("talon_search", "search query: " + mQuery);
                query = new Query();

                if (mQuery.contains(" TOP")) {
                    query.setResultType(Query.ResultType.popular);
                }

                query.setQuery(mQuery.replace(" TOP", ""));
                QueryResult result;
                try {
                    result = twitter.search(query);
                } catch (OutOfMemoryError e) {
                    return;
                }

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

            }
        }
    }).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);
    }//from w  w  w  . j  av a2  s.  c om

    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  w  w  . j ava  2s.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.klinker.android.twitter.ui.drawer_activities.discover.NearbyTweets.java

License:Apache License

public void getTweets() {

    canRefresh = false;/* w w  w .j a va2s  .c om*/

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Twitter twitter = Utils.getTwitter(context, DrawerActivity.settings);

                boolean manualLoc = sharedPrefs.getBoolean("manually_config_location", false);

                int i = 0;
                while (!connected && i < 5 && !manualLoc) {
                    try {
                        Thread.sleep(1500);
                    } catch (Exception e) {

                    }

                    i++;
                }

                double latitude = -1;
                double longitude = -1;

                if (manualLoc) {
                    // need to query yahoos api for the location...
                    double[] loc = getLocationFromYahoo(sharedPrefs.getInt("woeid", 2379574));
                    latitude = loc[0];
                    longitude = loc[1];
                } else {
                    // set it from the location client
                    Location location = mLocationClient.getLastLocation();
                    latitude = location.getLatitude();
                    longitude = location.getLongitude();
                }

                query = new Query();
                query.setGeoCode(new GeoLocation(latitude, longitude), 10, Query.MILES);

                QueryResult result = twitter.search(query);

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

                for (Status s : result.getTweets()) {
                    statuses.add(s);
                }

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

                        LinearLayout spinner = (LinearLayout) layout.findViewById(R.id.list_progress);
                        spinner.setVisibility(View.GONE);
                    }
                });
            } catch (Throwable e) {
                e.printStackTrace();
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Toast.makeText(context, getString(R.string.error), Toast.LENGTH_SHORT).show();
                        } catch (IllegalStateException e) {
                            // not attached to activity
                        }
                    }
                });
            }

            canRefresh = true;
        }
    }).start();
}

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

License:Apache License

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

    new Thread(new Runnable() {
        @Override/*from  w ww.j  a va  2  s .co m*/
        public void run() {
            try {
                Twitter twitter = Utils.getTwitter(context, settings);

                query = new Query();

                if (mQuery.contains(" TOP")) {
                    query.setResultType(Query.ResultType.popular);
                }

                query.setQuery(mQuery.replace(" TOP", ""));
                QueryResult result;
                try {
                    result = twitter.search(query);
                } catch (OutOfMemoryError e) {
                    return;
                }

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

            }
        }
    }).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;
    ArrayList<Status> retrieved_tweets = new ArrayList<Status>();
    do {/*  ww  w  .  j a v  a 2 s. c o m*/
        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;
}