patternjavaMinor
Accessing tweets from Twitter API
Viewed 0 times
twittertweetsfromapiaccessing
Problem
I need help making this code more efficient but still functions the same, such as by making it access the Twitter API fewer times. When I run this code for like 1 min, I get an error from Twitter saying that it exceeds limits.
List tweets = result.getTweets();
for (Status tweet : tweets) {
if(!(tweet.getUser().getScreenName().toString().equals("gh") || tweet.getUser().getScreenName().toString().equals("gh"))){
boolean found = false;
List Stats= tw.getHomeTimeline();
for (Status StatList : Stats) {
if(StatList.getTweetText().equals(tweet.getTweetText())){
found = true;
break;
try {
System.out.println(tweet.getUser().getScreenName() );
Thread.sleep(2000);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}else{
// nothing here
}
}
if (found) // you can move this and the initialisation(boolean found = false) out side the upper if statement
System.out.println("false");
else
System.out.println("turn");
}else{
System.out.println("blocked");
}
}Solution
Just a few hints that might better the code:
-
If you tend to access a structure for a given element multiple times with an operation on it, extract it in a local variable:
-
Have try..catch for statements that can cause the exception i.e put this out
-
As your comment states, put the
-
Check if
-
Check if
-
If you tend to access a structure for a given element multiple times with an operation on it, extract it in a local variable:
tweet.getUser().getScreenName() // If its String, toString not required.-
Have try..catch for statements that can cause the exception i.e put this out
System.out.println(tweet.getUser().getScreenName() );-
As your comment states, put the
boolean out with the two states and have minimal print statements. If its for debugging, add comments or debug flag.- Having try..catch after break? Please check.
-
Check if
tweets is null afterList tweets = result.getTweets();-
Check if
tweet is null inside the for loop.- Apply (5) and (6) for Stats as well.
Code Snippets
tweet.getUser().getScreenName() // If its String, toString not required.System.out.println(tweet.getUser().getScreenName() );List<Status> tweets = result.getTweets();Context
StackExchange Code Review Q#71987, answer score: 2
Revisions (0)
No revisions yet.