Example usage for twitter4j GeoLocation GeoLocation

List of usage examples for twitter4j GeoLocation GeoLocation

Introduction

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

Prototype

public GeoLocation(double latitude, double longitude) 

Source Link

Document

Creates a GeoLocation instance

Usage

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

License:Apache License

private boolean updateText(String text, long tweet_id, boolean useGeo) {
    StatusUpdate statusUpdate = new StatusUpdate(text);
    if (useGeo) {
        Location loc = LocationUtils.getLastLocation(getContext());
        GeoLocation gl = new GeoLocation(loc.getLatitude(), loc.getLongitude());
        statusUpdate.setLocation(gl);/*w  w w . ja  va  2  s  .  c o m*/
    }
    if (tweet_id > 0)
        statusUpdate.inReplyToStatusId(tweet_id);
    try {
        twitter.updateStatus(statusUpdate);
    } catch (TwitterException e) {
        e.printStackTrace();
        return false;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

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

License:Apache License

@Override
public BaseResponse loadInBackground() {

    //TODO: Comprobar el valor devuelto con el valor esperado (error - ready) y el parmetro user_geolocation
    try {/* ww  w.ja v  a  2s  .c om*/
        Log.d(Utils.TAG, "Enviando a twitlonger: " + tweet_text);

        String textTwitLonger = "";

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://www.twitlonger.com/api_post");

        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
            nameValuePairs.add(new BasicNameValuePair("application", "tweettopics"));
            nameValuePairs.add(new BasicNameValuePair("api_key", "f7y8lgz31srR46sr"));
            nameValuePairs.add(new BasicNameValuePair("username", twitter.getScreenName()));
            nameValuePairs.add(new BasicNameValuePair("message", tweet_text));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
            HttpResponse httpResponse = httpclient.execute(httppost);

            String xml = EntityUtils.toString(httpResponse.getEntity());

            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            factory.setNamespaceAware(true);
            XmlPullParser x = factory.newPullParser();

            x.setInput(new StringReader(xml));

            String error = "";

            int eventType = x.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                if (eventType == XmlPullParser.START_TAG) {
                    if (x.getName().equals("error")) {
                        error = x.nextText();
                    }
                    if (x.getName().equals("content")) {
                        textTwitLonger = x.nextText();
                        Log.d(Utils.TAG, "Enviando a twitter: " + textTwitLonger);
                    }
                }
                eventType = x.next();
            }

            if (!error.equals("")) {
                Log.d(Utils.TAG, "Error: " + error);
                ErrorResponse response = new ErrorResponse();
                response.setError(error);
                return response;
            }
        } catch (Exception e) {
            e.printStackTrace();
            ErrorResponse response = new ErrorResponse();
            response.setError(e, e.getMessage());
            return response;
        }

        UploadTwitlongerResponse response = new UploadTwitlongerResponse();

        if (!textTwitLonger.equals("")) {
            StatusUpdate statusUpdate = new StatusUpdate(textTwitLonger);
            if (use_geolocation) {
                Location loc = LocationUtils.getLastLocation(getContext());
                GeoLocation gl = new GeoLocation(loc.getLatitude(), loc.getLongitude());
                statusUpdate.setLocation(gl);
            }
            if (tweet_id > 0)
                statusUpdate.inReplyToStatusId(tweet_id);
            twitter.updateStatus(statusUpdate);

            response.setReady(true);
        } else {
            response.setReady(false);
        }

        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 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);
    }/*  www .j  a v  a 2s .  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.javielinux.task.UploadStatusAsyncTask.java

License:Apache License

private boolean updateText(String text, long tweet_id, boolean useGeo) {
    StatusUpdate su = new StatusUpdate(text);
    if (useGeo) {
        Location loc = LocationUtils.getLastLocation(mContext);
        GeoLocation gl = new GeoLocation(loc.getLatitude(), loc.getLongitude());
        su.setLocation(gl);//from w w  w  . j  ava2s. c o m
    }
    if (tweet_id > 0)
        su.inReplyToStatusId(tweet_id);
    try {
        twitter.updateStatus(su);
    } catch (TwitterException e) {
        e.printStackTrace();
        return false;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:com.javielinux.task.UploadTwitlongerAsyncTask.java

License:Apache License

@Override
protected Boolean doInBackground(String... args) {
    try {/*  w  w  w .  j  a  v  a2 s.co  m*/
        String text = args[0];
        Log.d(Utils.TAG, "Enviando a twitlonger: " + text);
        long tweet_id = Long.parseLong(args[1]);
        boolean useGeo = args[2].equals("1") ? true : false;

        String textTwitLonger = "";

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://www.twitlonger.com/api_post");
        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
            nameValuePairs.add(new BasicNameValuePair("application", "tweettopics"));
            nameValuePairs.add(new BasicNameValuePair("api_key", "f7y8lgz31srR46sr"));
            nameValuePairs.add(new BasicNameValuePair("username", twitter.getScreenName()));

            //byte[] utf8Bytes = text.getBytes("UTF8");
            //String textutf8 = new String(utf8Bytes, "UTF8");
            nameValuePairs.add(new BasicNameValuePair("message", text));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
            HttpResponse httpResponse = httpclient.execute(httppost);

            String xml = EntityUtils.toString(httpResponse.getEntity());
            try {

                XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
                factory.setNamespaceAware(true);
                XmlPullParser x = factory.newPullParser();

                x.setInput(new StringReader(xml));

                String error = "";

                int eventType = x.getEventType();
                while (eventType != XmlPullParser.END_DOCUMENT) {
                    if (eventType == XmlPullParser.START_TAG) {
                        if (x.getName().equals("error")) {
                            error = x.nextText();
                        }
                        if (x.getName().equals("content")) {
                            textTwitLonger = x.nextText();
                            Log.d(Utils.TAG, "Enviando a twitter: " + textTwitLonger);
                        }
                    }
                    eventType = x.next();
                }

                if (!error.equals("")) {
                    Log.d(Utils.TAG, "Error: " + error);
                    return true;
                }

            } catch (Exception e) {
                e.printStackTrace();
                return true;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return true;
        }

        if (!textTwitLonger.equals("")) {
            StatusUpdate su = new StatusUpdate(textTwitLonger);
            if (useGeo) {
                Location loc = LocationUtils.getLastLocation(mContext);
                GeoLocation gl = new GeoLocation(loc.getLatitude(), loc.getLongitude());
                su.setLocation(gl);
            }
            if (tweet_id > 0)
                su.inReplyToStatusId(tweet_id);
            twitter.updateStatus(su);
        } else {
            return true;
        }

        //} catch (TwitterException e) {
        //   e.printStackTrace();
        //   return true;
    } catch (Exception e) {
        e.printStackTrace();
        return true;
    }
    return false;
}

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

License:Apache License

public void getTrends() {

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

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

                    }

                    i++;
                }

                twitter4j.Trends trends;

                if (sharedPrefs.getBoolean("manually_config_location", false)) {
                    trends = twitter.getPlaceTrends(sharedPrefs.getInt("woeid", 2379574)); // chicago to default
                } else {
                    Location location = mLastLocation;

                    ResponseList<twitter4j.Location> locations = twitter
                            .getClosestTrends(new GeoLocation(location.getLatitude(), location.getLongitude()));
                    trends = twitter.getPlaceTrends(locations.get(0).getWoeid());
                }

                final ArrayList<String> currentTrends = new ArrayList<String>();

                for (Trend t : trends.getTrends()) {
                    String name = t.getName();
                    currentTrends.add(name);
                }

                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            if (currentTrends != null) {
                                listView.setAdapter(new TrendsArrayAdapter(context, currentTrends));
                                listView.setVisibility(View.VISIBLE);
                            } else {
                                Toast.makeText(context, getResources().getString(R.string.no_location),
                                        Toast.LENGTH_SHORT).show();
                            }

                            LinearLayout spinner = (LinearLayout) layout.findViewById(R.id.list_progress);
                            spinner.setVisibility(View.GONE);
                        } catch (Exception e) {
                            // not attached to activity
                        }
                    }
                });

                HashtagDataSource source = HashtagDataSource.getInstance(context);

                for (String s : currentTrends) {
                    Log.v("talon_hashtag", "trend: " + s);
                    if (s.contains("#")) {
                        // we want to add it to the auto complete
                        Log.v("talon_hashtag", "adding: " + s);

                        // could be much more efficient by querying and checking first, but I
                        // just didn't feel like it when there is only ever 10 of them here
                        source.deleteTag(s);

                        // add it to the userAutoComplete database
                        source.createTag(s);
                    }
                }

            } catch (Throwable e) {
                e.printStackTrace();
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Toast.makeText(context, getResources().getString(R.string.no_location),
                                    Toast.LENGTH_SHORT).show();
                        } catch (Exception e) {
                            // not attached to activity
                        }
                    }
                });
            }
        }
    }).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 va 2  s .co m*/

    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.LocalTrends.java

License:Apache License

public void getTrends() {

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

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

                    }

                    i++;
                }

                twitter4j.Trends trends;

                if (sharedPrefs.getBoolean("manually_config_location", false)) {
                    trends = twitter.getPlaceTrends(sharedPrefs.getInt("woeid", 2379574)); // chicago to default
                } else {
                    Location location = mLocationClient.getLastLocation();

                    ResponseList<twitter4j.Location> locations = twitter
                            .getClosestTrends(new GeoLocation(location.getLatitude(), location.getLongitude()));
                    trends = twitter.getPlaceTrends(locations.get(0).getWoeid());
                }

                final ArrayList<String> currentTrends = new ArrayList<String>();

                for (Trend t : trends.getTrends()) {
                    String name = t.getName();
                    currentTrends.add(name);
                }

                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            if (currentTrends != null) {
                                listView.setAdapter(new TrendsArrayAdapter(context, currentTrends));
                                listView.setVisibility(View.VISIBLE);
                            } else {
                                Toast.makeText(context, getResources().getString(R.string.no_location),
                                        Toast.LENGTH_SHORT).show();
                            }

                            LinearLayout spinner = (LinearLayout) layout.findViewById(R.id.list_progress);
                            spinner.setVisibility(View.GONE);
                        } catch (Exception e) {
                            // not attached to activity
                        }
                    }
                });

                HashtagDataSource source = HashtagDataSource.getInstance(context);

                for (String s : currentTrends) {
                    Log.v("talon_hashtag", "trend: " + s);
                    if (s.contains("#")) {
                        // we want to add it to the auto complete
                        Log.v("talon_hashtag", "adding: " + s);

                        // could be much more efficient by querying and checking first, but I
                        // just didn't feel like it when there is only ever 10 of them here
                        source.deleteTag(s);

                        // add it to the userAutoComplete database
                        source.createTag(s);
                    }
                }

            } catch (Throwable e) {
                e.printStackTrace();
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Toast.makeText(context, getResources().getString(R.string.no_location),
                                    Toast.LENGTH_SHORT).show();
                        } catch (Exception e) {
                            // not attached to activity
                        }
                    }
                });
            }
        }
    }).start();
}

From source file:crawling.FoundUsersBySearchGeo.java

License:Apache License

public static void main(String[] args) {

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            /* my shutdown code here */
            // Record the user status
            out.println("Final status -------------------:");
            for (Long id : discoveredUsers.keySet()) {
                out.println(id + "," + discoveredUsers.get(id));
            }//from  ww w. j  ava  2  s  .c  o m
            out.close();

            DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            Date date = new Date();
            date = new Date();
            System.out.println("End at: " + dateFormat.format(date));
        }
    });

    if (args.length < 5) {
        System.out.println("Usage: java twitter4j.examples.PrintFilterStreamGeo lati long radius unit CITY");
        System.exit(-1);
    }
    if (args.length == 6) {
        // Preload the collected user IDs
        preloadID(args[5]);
    }

    try {
        FileWriter outFile = new FileWriter("discoveredUser" + args[4] + ".txt", true);
        out = new PrintWriter(outFile);
        //out.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    avgUsers = new int[histCount];

    Query query = new Query();
    query.setGeoCode(new GeoLocation(Double.parseDouble(args[0]), Double.parseDouble(args[1])),
            Double.parseDouble(args[2]), args[3]);
    // New York Metropolitan
    //query.setGeoCode(new GeoLocation(40.7, -74), 100, "km");
    // Bay Area MetroPolitan
    //query.setGeoCode(new GeoLocation(37.78, -122.4), 100, "km");
    // LA MetroPolitan
    //query.setGeoCode(new GeoLocation(34.05, -118.24), 200, "km");

    query.setCount(100);
    //query.setPage(20);

    //Twitter twitter = new TwitterFactory().getInstance();
    Twitter twitter = getOAuthTwitter();

    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Date date = new Date();
    //System.out.println();
    System.out.println("----------------------------------------------");
    System.out.println("Start at: " + dateFormat.format(date));

    while (true) {
        //for (int i = 1; i <= 15; i ++){
        //   query.setPage(i);
        try {
            doASearch(twitter, query);
        } catch (TwitterException te) {
            // TODO Auto-generated catch block
            te.printStackTrace();
            System.out.println("Failed to search tweets: " + te.getMessage());

            // back-off
            Thread.currentThread();
            try {
                Thread.sleep(60 * 1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        Thread.currentThread();
        try {
            Thread.sleep(5 * 1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:crawltweets2mongo.MonoThread.java

@Override
public void run() {
    String keyword = "university of queensland";
    double latitude = -27.471;
    double longitude = 153.0234;
    double radius = 200;

    GeoLocation myLoc = new GeoLocation(latitude, longitude);
    GeoLocation GattonLoc = new GeoLocation(-27.560802, 152.344739);
    while (true) {
        try {/* w ww  . ja v a 2 s.  c o  m*/
            System.out.println("catch key word-------------------------");
            getNewTweets(keyword);

            sleep(19000);
            getNewTweets(myLoc, radius);
            sleep(19000);
            System.out.println("catch Gatton location-------------------------");
            getNewTweets(GattonLoc, 100);
            sleep(19000);
            getNewTweets(" uq ");
            sleep(19000);
            getNewTweets("St Lucia");
            sleep(19000);

        } catch (InterruptedException ex) {
            java.util.logging.Logger.getLogger(MonoThread.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}