Collecting Tweets Using a Geolocation Bounding Box Using Java (Twitter4j)

This code collects Tweets in an area around Galway, Ireland. The one thing to notice here (and something that baffled me for a while) is that while it returns (latitude, longitude), the bounding box is defined as {{longitude1,latitude1},{longitude2,latitude2}} as answered here

This is using Twitter4j 3.0.3 Core and Stream.

package me.davidcrowley.deri.geotweets;

import java.util.Date;

import twitter4j.FilterQuery;
import twitter4j.GeoLocation;
import twitter4j.Place;
import twitter4j.StallWarning;
import twitter4j.Status;
import twitter4j.StatusDeletionNotice;
import twitter4j.StatusListener;
import twitter4j.TwitterStream;
import twitter4j.TwitterStreamFactory;
import twitter4j.User;
import twitter4j.conf.ConfigurationBuilder;

public class GeoTweets {
	public static void main(String[] args) {
		ConfigurationBuilder cb = new ConfigurationBuilder();
		cb.setDebugEnabled(true);
		cb.setOAuthConsumerKey("xxxxxx");
		cb.setOAuthConsumerSecret("xxxxx");
		cb.setOAuthAccessToken("xxxxx");
		cb.setOAuthAccessTokenSecret("xxxxx");

		TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();

		StatusListener listener = new StatusListener() {

			@Override
			public void onException(Exception arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onDeletionNotice(StatusDeletionNotice arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onScrubGeo(long arg0, long arg1) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onStatus(Status status) {
				User user = status.getUser();

				// gets Username
				String username = status.getUser().getScreenName();
				System.out.println(username);
				String profileLocation = user.getLocation();
				System.out.println(profileLocation);
				long tweetId = status.getId(); 
				System.out.println(tweetId);
				String content = status.getText();
				System.out.println(content);
				GeoLocation geolocation = status.getGeoLocation();
				double tweetLatitude = geolocation.getLatitude();
				double tweetLongitude = geolocation.getLongitude();

				String application = status.getSource();
				System.out.println(application);

				Place placenameJSON = status.getPlace();
				System.out.println(placenameJSON);
				String placename = placenameJSON.getFullName();
				System.out.println(placename);
				Date time = status.getCreatedAt();
				System.out.println(time);

				System.out.println(tweetLatitude + "," + tweetLongitude +"\n");
			}

			@Override
			public void onTrackLimitationNotice(int arg0) {
				// TODO Auto-generated method stub
				System.out.println("onTrackLimitationNotice" +"\n");

			}

			@Override
			public void onStallWarning(StallWarning arg0) {
				// TODO Auto-generated method stub
				System.out.println("onStallWarning" +"\n");

			}

		};
		FilterQuery fq = new FilterQuery();
		double lat = 53.270141;
		double longitude = -9.055488;
		double lat1 = lat - .25;
		double longitude1 = longitude - .25;
		double lat2 = lat + .25;
		double longitude2 = longitude + .25;
		twitterStream.addListener(listener);
		double[][] bb= {{longitude1, lat1}, {longitude2, lat2}};

		fq.locations(bb);

		twitterStream.filter(fq);  

	}
}

Android Twitter oAuth with Twitter4j (without signpost)

Basic Code for Twitter oAuth for Android works with any version of Android I have tested it against – will crash if no Internet access but adding a check for this is relevantly simple (wanted to keep the code just about the oAuth process – the core idea and code comes from this blogpost

AndroidBasicOAuthActivity Code

package me.crowleydavid.android.basicoauth;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class AndroidBasicOAuthActivity extends Activity {
    private int TWITTER_AUTH;
    private Twitter mTwitter;
    private RequestToken mRequestToken;

    private String accessToken;
    private String accessTokenSecret;

    private boolean haveConnectedWifi;
    private boolean haveConnectedMobile;
    private double x;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
        accessToken = settings.getString( "twitter_access_token", null );
        accessTokenSecret = settings.getString( "twitter_access_token_secret", null );
        Button tweetB = (Button) findViewById(R.id.tweet_button);
        tweetB.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                updateStatus();

            }
        });

    }
    private boolean haveNetworkConnection() {
        haveConnectedWifi = false;
        haveConnectedMobile = false;

        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();
        for (NetworkInfo ni : netInfo) {
            if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                if (ni.isConnected())
                    haveConnectedWifi = true;
            if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                if (ni.isConnected())
                    haveConnectedMobile = true;
        }
        return haveConnectedWifi || haveConnectedMobile;
    }

// private void updateStatusLoggedIn() {
// SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
// accessToken = settings.getString( "twitter_access_token", null );
// accessTokenSecret = settings.getString( "twitter_access_token_secret", null );
//
// // String s2 = String.valueOf(i);
// // Toast.makeText(this, s2, 10000).show();
// ConfigurationBuilder builder = new ConfigurationBuilder();
// builder.setOAuthConsumerKey(Constants.CONSUMER_KEY);
// builder.setOAuthConsumerSecret(Constants.CONSUMER_SECRET);
// builder.setOAuthAccessToken(accessToken);
// builder.setOAuthAccessTokenSecret(accessTokenSecret);
// Configuration conf = builder.build();
// Twitter t = new TwitterFactory(conf).getInstance();
// i++;
// try {
// if(i<10){
// t.updateStatus( "Loggedin" + i);
// }
// }
// catch (TwitterException e) {
// e.printStackTrace();
// }
//
// }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub

        if (requestCode == TWITTER_AUTH)
        {

            if (resultCode == Activity.RESULT_OK)
            {
                Toast.makeText(this, "Hey Ho", 300).show();
                String oauthVerifier = (String) data.getExtras().get("oauth_verifier");

                AccessToken at = null;

                try
                {
                    // Pair up our request with the response
                    at = mTwitter.getOAuthAccessToken(oauthVerifier);
                    String theToken = at.getToken();
                    // Toast.makeText(this, theToken, 10000).show();
                    String theTokenSecret = at.getTokenSecret();
                    // Toast.makeText(this, theTokenSecret, 10000).show();
                    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
                    settings = PreferenceManager.getDefaultSharedPreferences(this);
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putString("twitter_access_token",theToken);
                    editor.putString("twitter_access_token_secret", theTokenSecret);
                    editor.commit();

                    // his method
                    // settings.edit()
                    // .putString( "twitter_access_token", at.getToken() )
                    // .putString( "twitter_access_token_secret", at.getTokenSecret() )
                    // .commit();
                    // Intent i = new Intent(this, someclass.class);
                    // startActivity(i);

                    updateStatus();
                }
                catch (TwitterException e)
                {
                    e.printStackTrace();
                }
            }
        }
        else
        {
            Toast.makeText(this, "uh oh, Spaghetti Os", 300).show();
        }

    }
    private void updateStatus() {
        // TODO Auto-generated method stub
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
        accessToken = settings.getString( "twitter_access_token", null );
        accessTokenSecret = settings.getString( "twitter_access_token_secret", null );
        // Toast.makeText(this, accessToken, 10000).show();
        // Toast.makeText(this, accessTokenSecret, 10000).show();
        haveNetworkConnection();
        if ((haveConnectedWifi)|| (haveConnectedMobile)){
            ConfigurationBuilder builder = new ConfigurationBuilder();
            builder.setOAuthConsumerKey(Constants.CONSUMER_KEY);
            builder.setOAuthConsumerSecret(Constants.CONSUMER_SECRET);
            builder.setOAuthAccessToken(accessToken);
            builder.setOAuthAccessTokenSecret(accessTokenSecret);
            Configuration conf = builder.build();
            Twitter t = new TwitterFactory(conf).getInstance();

            try {
                x = Math.random();
                t.updateStatus( "Yo ho ho and a bottle of rum " + x);

            }
            catch (TwitterException e) {
                e.printStackTrace();
            }
        }
        else{
            Toast.makeText(this, "No access to Internet..please try again", 3000).show();
        }
    }
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);

        accessToken = settings.getString( "twitter_access_token", null );
        accessTokenSecret = settings.getString( "twitter_access_token_secret", null );
        haveNetworkConnection();
        if ((haveConnectedWifi)|| (haveConnectedMobile)){
            // Toast.makeText(this, "Internet is go!", 3000).show();
            // Intent i = new Intent(this, AndroidBasicOAuthActivity.class);
            // startActivity(i);

            if ((accessToken==null)||(accessTokenSecret==null)){
                mTwitter = new TwitterFactory().getInstance();
                mRequestToken = null;
                mTwitter.setOAuthConsumer(Constants.CONSUMER_KEY,Constants.CONSUMER_SECRET );
                String callbackURL = getResources().getString(R.string.twitter_callback);
                try
                {
                    mRequestToken = mTwitter.getOAuthRequestToken(callbackURL);
                }
                catch (TwitterException e)
                {
                    e.printStackTrace();
                }
                Intent i = new Intent(this, TwitterWebviewActivity.class);
                i.putExtra("URL", mRequestToken.getAuthenticationURL());
                startActivityForResult(i, TWITTER_AUTH);
            }
            else{
                Toast.makeText(this, "Token found..logged in", 3000).show();
                // updateStatusLoggedIn();
            }
        }
        else{
            Toast.makeText(this, "No access to Internet..please try again", 3000).show();
            Intent i = new Intent(this, CheckNetAccess.class);
            startActivity(i);
        }
    }
}

Constants Code you need to enter your own Twitter Developer keys here

package me.crowleydavid.android.basicoauth;

public class Constants {

    public static final String CONSUMER_KEY = "************";
    public static final String CONSUMER_SECRET= "**************";

TwitterWebviewActivity Code
package me.crowleydavid.android.basicoauth;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class TwitterWebviewActivity extends Activity {
    private Intent mIntent;
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.twitter_webview);
        mIntent = getIntent();
        String url = (String)mIntent.getExtras().get("URL");
        WebView webView = (WebView) findViewById(R.id.webview);
        webView.setWebViewClient( new WebViewClient()
        {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url)
            {
                if( url.contains(getResources().getString( R.string.twitter_callback )))
                {
                    Uri uri = Uri.parse( url );
                    String oauthVerifier = uri.getQueryParameter( "oauth_verifier" );
                    mIntent.putExtra( "oauth_verifier", oauthVerifier );
                    setResult( RESULT_OK, mIntent );
                    finish();
                    return true;
                }
                return false;
            }
        });
        webView.loadUrl(url);
    }
}

}

CheckNetAccess Code

package me.crowleydavid.android.basicoauth;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class CheckNetAccess extends Activity {
    private boolean haveConnectedWifi;
    private boolean haveConnectedMobile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.checknet);
        Button netB = (Button) findViewById(R.id.netbutton);
        netB.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                haveNetworkConnection();
                if ((haveConnectedWifi)|| (haveConnectedMobile)){
                    Toast.makeText(CheckNetAccess.this, "Internet is go!", 3000).show();
                    Intent i = new Intent(CheckNetAccess.this, AndroidBasicOAuthActivity.class);
                    startActivity(i);
                }
                else{
                    Toast.makeText(CheckNetAccess.this, "No access to Internet..please try again", 3000).show();
                }
            }
        });

    }

    private boolean haveNetworkConnection() {
        haveConnectedWifi = false;
        haveConnectedMobile = false;

        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();
        for (NetworkInfo ni : netInfo) {
            if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                if (ni.isConnected())
                    haveConnectedWifi = true;
            if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                if (ni.isConnected())
                    haveConnectedMobile = true;
        }
        return haveConnectedWifi || haveConnectedMobile;
    }
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
    }

}

Android Manifest needs these permissions

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

AndroidBasicOAuth