Quick Tutorial: Twitter & Processing

Accessing information from the Twitter API with Processing is easy. A few people have sent me e-mails asking how it all works, so I thought I’d write a very quick tutorial to get everyone up on their feet.

We don’t need to know too much about how the Twitter API functions, because someone has put together a very useful Java library to do all of the dirty work for us. It’s called twitter4j, and you can download it here. Once you have it downloaded, we can get started.

1. Open up a new Processing sketch.
2. Import the twitter4j library – you do this by simply dragging the twitter4j-2.0.8.jar file onto your sketch window. If you want to check, you should now see this file in your sketch folder, inside of a new ‘code’ directory.
3. We’ll put the guts of this example into the setup enclosure, but you could wrap it into a function or build a simple Class around it if you’d like:

Twitter myTwitter;

void setup() {
  myTwitter = new Twitter("yourTwitterUserName", "yourTwitterPassword");
};

void draw() {
  
};

4. Now that we have a Twitter object, we want to build a query to search via the Twitter API for a specific term or phrase. This is code that will not always work – sometimes the Twitter API might be down, or our search might not return any results, or we might not be connected to the internet. The Twitter object in twitter4j handles those types of conditions by throwing back an exception to us; we need to have a try/catch structure ready to deal with that if it happens:

Twitter myTwitter;

void setup() {
  myTwitter = new Twitter("yourTwitterUserName", "yourTwitterPassword");
  try {
    
    Query query = new Query("sandwich");
    QueryResult result = myTwitter.search(query);    

  }
  catch (TwitterException te) {
    println("Couldn't connect: " + te);
  };
};
void draw() {
  
};

5. This code is working – but we haven’t done anything with the results. Here, we’ll set the results per page parameter for the query to 100 to get the last 100 results with the term ‘sandwich’ and spit those results into the output panel:

Twitter myTwitter;

void setup() {
  myTwitter = new Twitter("yourTwitterUserName", "yourTwitterPassword");
  try {
    
    Query query = new Query("sandwich");
    query.setRpp(100);
    QueryResult result = myTwitter.search(query);
    
    ArrayList tweets = (ArrayList) result.getTweets();
    
    for (int i = 0; i < tweets.size(); i++) {
      Tweet t = (Tweet) tweets.get(i);
      String user = t.getFromUser();
      String msg = t.getText();
      Date d = t.getCreatedAt();
      println("Tweet by " + user + " at " + d + ": " + msg);
    };
    
  }
  catch (TwitterException te) {
    println("Couldn't connect: " + te);
  };
};

void draw() {
  
};

That’s it! This example is very simple, but it’s the bare bones of what you need build a project which connects Twitter through Processing. Good luck!

46 thoughts on “Quick Tutorial: Twitter & Processing”

  1. One of these days I'll be able to figure this stuff out. I got lost at 'open up a new processing sketch'!

    That gets me every time; like html, I don't know how to start there either. Funny thing though I seem to understand most everything else I read here. Must be a stupid thingy with me.

    Excellent blog though, the stuff you've created looks really good.

    1. if you check out Processing.org, that will explain everything you need to get going. You probably didn't realize that processing is an application to write and compile code, written in the Processing language. Once you have the application downloaded, opening the application automatically starts a new window which is called a Sketch. Sounds like you can handle the tougher parts :)

  2. I'm having problems with the constructor :S

    i put this on processing and this have to work but it hasn't >.<

    Twitter miTwitter;
    String user = "user";
    String pass = "pass";
    miTwitter = new Twitter(user, pass);

    I do the steps 1 & 2 whitout problems … but when i get to the step 3 in the fourth line it say that the constructor Twitter(string,string) is undefined

    Any suggestion please ??

    Thanks for the blog it's really great and it helps me a lot.

  3. Very good tutorial, but i'm having problems with the constructor :

    String user = "user";
    String pass = "pass";
    Twitter miTwitter = new Twitter(user, pass);

    This generates an error : "The constructor Twitter(String,String) is undefined"

    Any suggestion ??

    Thanks.

  4. To let the error-message disappear, you have to open a new Processing pde-file. Then, just copy the code in it without doing anything. Before, you have to create a "twitter4j" directory in the "libraries" folder. In your new created twitter4j folder, you create another folder called "library". There, you put in the twitter4j.jar file (You have to rename it to "twitter4j.jar" first!). Then, click "Import library -> twitter4j" in your new processing file.

    1. I'm also having problems with the error: "The constructor Twitter(String,String) is undefined"

      I tried adding the twitter4j library as Cheddar suggested but it still gives the same problems.

      Anyone else have an idea whats going wrong?

      Thanx!

  5. I'm having a peoblem when exporting it from processing. It keeps giving me an error java.lang.NoClassDefFoundError: twitter4j/TwitterException I'm not sure why since all of my code is in the right folders, or I hope it is. I've asked around and no ne can seem to find an a reason why. i was hoping you crossed by it and can help me find it.

    1. i think you need to sign the applet. There is an easy step by step instruction at processing.org :

      http://processing.org/hacks/hacks:signapplet

      make sure you sign it for all of the jar files. however, once I got that error message out of the way, I am getting an Animation Thread exception in the twitter4j class for all of the functions it calls…so now im stuck again.

      1. Hi, I'm getting the same Animation thread exception:

        Exception in thread "Animation Thread" java.lang.NullPointerException
        at twitter4j.TwitterResponse.<init>(TwitterResponse.java:68)
        at twitter4j.QueryResult.<init>(QueryResult.java:57)
        at twitter4j.Twitter.search(Twitter.java:343)

        Any idea on how to fix it?

        thanks!

  6. also, you're going to have to go into the index file generated and where it says "Archive" = 'yourfile.jar' you need to add the twitter jar

  7. I have tried putting in the code and installing twitter4j into processing. I'm getting no error messages, but always get a Couldn't connect: twitter4j.TwitterException: connect timed out
    Is this message an internet connection problem with processing (login on browser works fine) or a problem with connecting to twitter?

    Can someone help please?

    1. Hi @davypaperboy. I am facing the same problem. Have you found a solution?

      My Twitter-Java application is on 1.4.2_05, and the Exception thrown is as below:
      java.lang.NoClassDefFoundError: java/net/Proxy
      at twitter4j.http.HttpClient.getConnection(HttpClient.java:409)
      at twitter4j.http.HttpClient.request(HttpClient.java:243)
      at twitter4j.http.HttpClientWrapper.request(HttpClientWrapper.java:66)
      at twitter4j.http.HttpClientWrapper.post(HttpClientWrapper.java:97)
      at twitter4j.Twitter.updateStatus(Twitter.java:428)

  8. Dear Jer, when i run the sketch i get static page with number of tweets, how would you implement self-updating tweets?

    i used ur code. Thank you!

    Twitter myTwitter;

    PFont fontA;

    void setup() {

    size(800,600);

    background(0);

    smooth();

    fontA = loadFont(“Baskerville-48.vlw”);

    textFont(fontA, 20);

    textAlign(LEFT, CENTER);

    noLoop();

    noStroke();

    };

    void draw() {

    myTwitter = new Twitter(“yourTwitterUserName”, “yourTwitterPassword”);

    try {

    Query query = new Query(“jer”);

    query.setRpp(40);

    QueryResult result = myTwitter.search(query);

    ArrayList tweets = (ArrayList) result.getTweets();

    for (int i = 0; i < tweets.size(); i++) {

    Tweet t = (Tweet) tweets.get(i);

    String user = t.getFromUser();

    String msg = t.getText();

    Date d = t.getCreatedAt();

    println("Tweet by " + user + " at " + d + ": " + msg);

    // println(msg);

    fill((127), (0), (0));

    colorMode(RGB,100,500,10, 255);

    text(msg, random(500), random(500),width/2, height/2);

    textAlign(CENTER);//posX = 100;

    //posY = 10;

    //text(msg,100*2 ,10+50 );

    };

    }

    catch (TwitterException te) {

    println("Couldn't connect: " + te);

    };

    };

    1. hi skwinte,
      I have been looking at Jer's sketch and your own and was wondering if you ever worked out how to implement self-updating tweets?
      many thanks

  9. hey nice work man, though i need ur help in posting to twitter using javascript and xml, im a novice in this and will really appreciate if u can help me out, cheers

  10. I must admit I am one of the few people that do not have a face book account. I have a twitter account, but have only really started to understand how powerful it can be by reading articles like this – cheers

  11. Any idea how to implement the new twitter streaming api ? It use json – and I would guess it wouldn't work like this script right ?

  12. hello.. someone can u help me please????i got two questions which are:
    1) how to add our website link into the status in twitter using java programming???
    2) how to upload image into the status in twitter using java programming???

  13. Thanks for this example! Please, could you give a brief example of limiting queries by date (using the "since" and "until" methods in twitter4j)? That would be a huge help, because I am struggling in this area.

    Thanks,
    Dan

  14. Okay this might sound a little dumb but my first problem is that I don't which .jar file I need to use when downloading the new 2.2.0 version. Should I use the old version or is there a way to use this tutorial with this new version.

  15. Thank you!!!
    I had problems with the twitter4j library before, I didn't know that I can add a jar just by dragging it into the sketch..
    Thank you, you mafe my evening! :)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>