I am new to java and I am currently trying to write an application to stream tweets using twitter4j. I have made some progress and am able to get the streams to a textbox. I am struggling with a few things though:
I want to be able to start the stream using a "Go"-button. I am sorta able to do this at the moment by placing the listening code inside the button class(?!).
But the thing is that I also want to be able to stop the streaming by removing the listener and to this is need to place the declaration of the listener outside the "Go"-button. Where should I place it?
I am also getting some compilation error on the line with "RateLimitStatus rateLimitStatus= twitter.getRateLimitStatus();" I can't understand why because when I used jCreatorLE this worked fine. Now I am using Netbeans and it isn't happy with something. The errorlightbulb is saying something like this "unreported exception twitter4.TwitterException; must be caught or declared to be thrown... Surround with... Introduce..." I take it has something to do with error catching? But how and where do I catch it?
I am grateful for any help at all! I hope I have provided enough info if not please let me know.
The code in its entirety:
/** * * @author Patricks */ import twitter4j.Status; import twitter4j.StatusDeletionNotice; import twitter4j.StatusListener; import twitter4j.TwitterException; import twitter4j.TwitterStream; import twitter4j.TwitterStreamFactory; import twitter4j.conf.ConfigurationBuilder; import twitter4j.Twitter; import twitter4j.RateLimitStatus; import twitter4j.TwitterFactory; public class TwitterAppGUI extends javax.swing.JFrame { /** * Creates new form TwitterAppGUI */ long noTweets =0; public TwitterAppGUI() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); jTextAreaOutput = new javax.swing.JTextArea(); jLabelNoTweets = new javax.swing.JLabel(); jButtonGo = new javax.swing.JButton(); jCheckBoxStoreTweets = new javax.swing.JCheckBox(); jButtonStop = new javax.swing.JButton(); jCheckBoxShowTweets = new javax.swing.JCheckBox(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jTextAreaOutput.setColumns(20); jTextAreaOutput.setEditable(false); jTextAreaOutput.setRows(10); jScrollPane1.setViewportView(jTextAreaOutput); jLabelNoTweets.setText("No. tweets:"); jButtonGo.setText("Go"); jButtonGo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonGoActionPerformed(evt); } }); jCheckBoxStoreTweets.setText("Store tweets in file"); jButtonStop.setText("Stop"); jButtonStop.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonStopActionPerformed(evt); } }); jCheckBoxShowTweets.setText("Show tweets"); jCheckBoxShowTweets.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxShowTweetsActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabelNoTweets) .addContainerGap()) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jCheckBoxStoreTweets) .addGroup(layout.createSequentialGroup() .addComponent(jButtonGo) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButtonStop)) .addComponent(jCheckBoxShowTweets)) .addGap(51, 51, 51) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 777, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 38, Short.MAX_VALUE)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabelNoTweets) .addGap(26, 26, 26) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(78, 78, 78) .addComponent(jCheckBoxStoreTweets) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBoxShowTweets) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButtonGo) .addComponent(jButtonStop))) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 424, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 8, Short.MAX_VALUE))) .addContainerGap()) ); pack(); }// </editor-fold> private void jButtonGoActionPerformed(java.awt.event.ActionEvent evt) { ListenTwitter(); } private void jButtonStopActionPerformed(java.awt.event.ActionEvent evt) { jTextAreaOutput.setText("testing"); // TODO add your handling code here: //this is where I would like to be able to stop the streaming } private void jCheckBoxShowTweetsActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } public void ListenTwitter(){ ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true); cb.setOAuthConsumerKey("bbb"); cb.setOAuthConsumerSecret("bbb"); cb.setOAuthAccessToken("bbb"); cb.setOAuthAccessTokenSecret("bbb"); TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance(); StatusListener listener = new StatusListener() { Twitter twitter= new TwitterFactory().getInstance(); RateLimitStatus rateLimitStatus= twitter.getRateLimitStatus(); public void onStatus(Status status) { // jTextAreaOutput.setText(); noTweets=noTweets+1; jLabelNoTweets.setText("No. tweets: " + noTweets); if(jCheckBoxShowTweets.isSelected()){ jTextAreaOutput.setText(jTextAreaOutput.getText() + "Tweetrelated:" +"\n"); jTextAreaOutput.setText(jTextAreaOutput.getText() +"....................."+"\n") ; jTextAreaOutput.setText(jTextAreaOutput.getText() +"Time: " + status.getCreatedAt()+"\n"); jTextAreaOutput.setText(jTextAreaOutput.getText() +"User: "+ status.getUser().getScreenName()+"\n"); jTextAreaOutput.setText(jTextAreaOutput.getText() +"Tweet: " + status.getText()+"\n"); // System.out.println("Geolocation: " + status.getGeoLocation()); // System.out.println("Place: " + status.getPlace()); jTextAreaOutput.setText(jTextAreaOutput.getText() +"\n"); jTextAreaOutput.setText("Twitter API related:"); jTextAreaOutput.setText("Hourly limit[RatelimitStatus]: " + rateLimitStatus.getHourlyLimit() ); jTextAreaOutput.setText("Remaininghits [RatelimitStatus]: " + rateLimitStatus.getRemainingHits() ); jTextAreaOutput.setText("ResetTime [RatelimitStatus]: " + rateLimitStatus.getResetTime()); jTextAreaOutput.setText("ResetTimeSeconds [Ratelimitstatus] : " + rateLimitStatus.getResetTimeInSeconds()); jTextAreaOutput.setText("SecondsUntilReset: [Ratelimitstatus] : " + rateLimitStatus.getSecondsUntilReset()); }//end if }//end onstatus public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { if(jCheckBoxShowTweets.isSelected()){ jTextAreaOutput.setText(jTextAreaOutput.getText() +"Got a status deletion notice id:" + statusDeletionNotice.getStatusId()+"\n"); }//end if } public void onTrackLimitationNotice(int numberOfLimitedStatuses) { if(jCheckBoxShowTweets.isSelected()){ jTextAreaOutput.setText(jTextAreaOutput.getText() +"Got track limitation notice:" + numberOfLimitedStatuses+"\n"); }//emd if } public void onScrubGeo(long userId, long upToStatusId) { if(jCheckBoxShowTweets.isSelected()){ jTextAreaOutput.setText(jTextAreaOutput.getText() +"Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId+"\n"); }//endif } public void onException(Exception ex) { ex.printStackTrace(); } }; twitterStream.addListener(listener); twitterStream.sample(); } /** * @param args the command line arguments */ public static void main(String args[]) { /* * Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* * If Nimbus (introduced in Java SE 6) is not available, stay with the * default look and feel. For details see * [url=http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html]How to Set the Look and Feel (The Java™ Tutorials > Creating a GUI With JFC/Swing > Modifying the Look and Feel)[/url] */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(TwitterAppGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TwitterAppGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TwitterAppGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TwitterAppGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* * Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new TwitterAppGUI().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton jButtonGo; private javax.swing.JButton jButtonStop; private javax.swing.JCheckBox jCheckBoxShowTweets; private javax.swing.JCheckBox jCheckBoxStoreTweets; private javax.swing.JLabel jLabelNoTweets; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTextAreaOutput; // End of variables declaration }