Scroll/Click Function - Processing 2 - Java - java

I am trying to add a scroll function to my code as currently it merely displays the first couple tweets, enough to fill the canvas but no more. How do I go about adding a scroll/click function so the canvas lists other tweets as well?
This is what I have so far with my Twitter API tokens omitted.
import java.util.Date;
import java.util.Arrays;
ArrayList<String> words = new ArrayList();
void setup() {
//Set the size of the stage, and the background to black.
size(750, 750);
background(0);
//Credentials
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey("x");
cb.setOAuthConsumerSecret("x");
cb.setOAuthAccessToken("x");
cb.setOAuthAccessTokenSecret("x");
TwitterFactory twitterFactory;
twitterFactory = new TwitterFactory(cb.build());
Twitter twitter = twitterFactory.getInstance();
Query query = new Query("StackOverFow");
query.count(100);
try {
QueryResult result = twitter.search(query);
ArrayList tweets = (ArrayList) result.getTweets();
for (int i = 0; i < tweets.size (); i++) {
Status t = (Status) tweets.get(i);
User u=(User) t.getUser();
String user=u.getName();
String msg = t.getText();
Date d = t.getCreatedAt();
text("User Name - " + user + " Time - " + d + " Message - " + msg,
20, 15+i*50, width-40, 50);
println("Tweet by " + user + " at " + d + ": " + msg);
//Break the tweet into words
String[] input = msg.split(" ");
println(input);
for (int j = 0; j < input.length; j++) {
//Put each word into the words ArrayList
words.add(input[j]);
}
};
}
catch (TwitterException te) {
println("Couldn't connect: " + te);
};
}
int j=0;
void mousePressed() {
saveData();
}
void saveData() {
String[] data = new String[words.size()];
words.toArray(data);
saveStrings("data/data.txt", data);
}

You already have a handler for mousePressed, adding click and scroll handling is the same concept: add mouseClicked for full click handling, and mouseWheel() for handling scroll events.

Related

Going to next activity once the list is complete

So I am working on a project and I don't know much about the android studio. So what I am doing is, I am using jsoup as my web parser and I am creating a list of products from e-commerce websites. So I want that once I get all the details from the parser, then my next activity starts. Till now I am using handler and setting some delay time in it. But that is not helping because sometimes it takes more than 3-4 seconds.
Below is the code by which I am sending the allproduct ArrayList and producturl ArrayList
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
Bundle args = new Bundle();
args.putSerializable("ARRAYLIST", (Serializable) allproducts);
args.putSerializable("URLLINKS", (Serializable) producturl);
intent.putExtra("BUNDLE", args);
intent.putExtra(EXTRA_TEXT, searchtext);
startActivity(intent);
}
}, 6500);
Sometimes the listview shows only 2 websites result and sometimes it shows every website.
private class Snapdeal extends AsyncTask<String, Void, ArrayList<String>> {
ArrayList<String> tempurlstore = new ArrayList<>();
String link;
#Override
protected void onPostExecute(ArrayList<String> s) {
String product;
String urlstore;
super.onPostExecute(s);
for (int j = 0; j < 6; j++) {
product = s.get(j);
urlstore = tempurlstore.get(j);
allproducts.add(product);
producturl.add(urlstore);
}
String seemore = "See more products on website....";
allproducts.add(seemore);
producturl.add(link);
}
#Override
protected ArrayList<String> doInBackground(String... strings) {
try {
Document doc = Jsoup.connect(strings[0]).get();
Elements links = doc.getElementsByClass("col-xs-6 favDp product-tuple-listing js-tuple ");
ArrayList<String> mainlist = new ArrayList<String>();
mainlist.add("SNAPDEAL");
link = strings[0];
tempurlstore.add("https://www.snapdeal.com");
for (Element link : links) {
String temp1 = null, temp2 = null, temp3 = null, temp4 = null, temp5 = null;
String permanent1 = null;
Elements elLink = link.getElementsByTag("a");
Elements eltitle = link.getElementsByClass("product-title"); //for product title
Elements elpricebefore = link.getElementsByClass("lfloat product-desc-price strike ");
Elements elpriceafter = link.getElementsByClass("lfloat product-price");
Elements discount = link.getElementsByClass("product-discount");
//product title loop
for (Element titleOfProduct : eltitle) {
temp1 = "Title: " + titleOfProduct.text();
}
//product original price loop
for (Element priceOfProductBefore : elpricebefore) {
temp2 = "Price before: " + priceOfProductBefore.text();
}
//product discounted price loop
for (Element priceOfProductAfter : elpriceafter) {
temp3 = "Discounted price: " + priceOfProductAfter.text();
}
//discount in number loop
for (Element productdiscount : discount) {
temp4 = "Discount: " + productdiscount.text();
}
ArrayList<String> linkArray = new ArrayList<String>();
for (Element elementLink : elLink) {
String MainLink = elementLink.attr("href");
linkArray.add(MainLink);
}
for (int j = 0; j < 1; j++) {
temp5 = linkArray.get(0);
}
if (elpricebefore.text()==null)
{
permanent1 = "\n" + temp1 + "\n" + "Price :" + elpriceafter.text() + "\n" + temp4 + "\n";
}
else
{
permanent1 ="\n" + temp1 + "\n" + temp2 + "\n" + temp3 + "\n" + temp4 + "\n";
}
mainlist.add(permanent1);
tempurlstore.add(temp5);
}
return mainlist;
} catch (Exception e) {
ArrayList<String> exception = new ArrayList<String>();
String ex = e.toString();
exception.add(ex);
return exception;
}
}
}
Above is some part of my project. So this is how I am taking all the products and all from the parser.
So how can I do this that once all the products are ready in the Arraylist then only intent gets started?
Please help. Thank you.
Why are you using a timer instead of a callback from your parser? This is creating a race condition which is at the heart of your issue. The only way around it is to fire your intent only after your parser is complete.
Without seeing the parser code it is tough to know the exact place to add your hook.
You shouldn't use a handler for that. What you could do is use an Observer or use Android's Live Data so the one you choose can let you know when the list is ready so you can start the activity.

Remove previous direction route on Google Maps

I'm using jd-alexander liabrary to show direction route on google map and my issue is, when I request another direction route, new route is created but previously created route is not removed. I want to remove the previous route and then show new route.
#Override
public void onRoutingSuccess(ArrayList<Route> routeArrayList, int i) {
//code to add route to map here.
polylines = new ArrayList<>();
if (polylines.size() > 0) {
erasePolylines();
}
polylines = new ArrayList<>();
//add route(s) to the map.
polylines.clear();
for (i = 0; i < routeArrayList.size(); i++) {
//In case of more than 5 alternative routes
int colorIndex = i % COLORS.length;
PolylineOptions polyOptions = new PolylineOptions();
polyOptions.color(getResources().getColor(COLORS[colorIndex]));
polyOptions.width(10 + i * 3);
polyOptions.addAll(routeArrayList.get(i).getPoints());
Polyline polyline = mMap.addPolyline(polyOptions);
polylines.add(polyline);
Toast.makeText(getApplicationContext(), "Route " + (i + 1) + ": distance - " + routeArrayList.get(i).
getDistanceValue() + ": duration - " + routeArrayList.get(i).getDurationValue(), Toast.LENGTH_SHORT).show();
}
}
private void erasePolylines(){
for(Polyline line : polylines){
line.remove();
}
polylines.clear();
}
How can I fix this?
polylines = new ArrayList<>();
if (polylines.size() > 0) {
for (Polyline poly : polylines) {
poly.remove();
}
erasePolylines();
}
polylines = new ArrayList<>();
//add route(s) to the map.
polylines.clear();
for (i = 0; i < routeArrayList.size(); i++) {
//In case of more than 5 alternative routes
int colorIndex = i % COLORS.length;
PolylineOptions polyOptions = new PolylineOptions();
polyOptions.color(getResources().getColor(COLORS[colorIndex]));
polyOptions.width(10 + i * 3);
polyOptions.addAll(routeArrayList.get(i).getPoints());
Polyline polyline = mMap.addPolyline(polyOptions);
polylines.add(polyline);
Toast.makeText(getApplicationContext(), "Route " + (i + 1) + ": distance - " + routeArrayList.get(i).
getDistanceValue() + ": duration - " + routeArrayList.get(i).getDurationValue(), Toast.LENGTH_SHORT).show();
}
}
Your code is ok, except here:
//You're initializing your list "POLILYNES" and trying remove empty list, Remove the
//lines I commented.
#Override
public void onRoutingSuccess(ArrayList<Route> routeArrayList, int i) {
//code to add route to map here.
polylines = new ArrayList<>(); // DELETE THIS LINE
if (polylines.size() > 0) {
erasePolylines();
}
polylines = new ArrayList<>(); // DELETE THIS LINE
//add route(s) to the map.
polylines.clear();
...
}

Get All User timeline tweets using twitter4j and java

I have a problem if anyone can help,
I'm trying to get tweets done by a specific user, here's my code:
Paging pg = new Paging();
String userName = "Obama";
pg.setCount(200);
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey("");
cb.setOAuthConsumerSecret("");
cb.setOAuthAccessToken("");
cb.setOAuthAccessTokenSecret("");
Twitter twitter = new TwitterFactory(cb.build()).getInstance();
int numberOfTweets = 1000000;
long lastID = Long.MAX_VALUE;
ArrayList<Status> tweets = new ArrayList<Status>();
while (tweets.size () < numberOfTweets) {
tweets.addAll(twitter.getUserTimeline(userName,pg));
//System.out.println("Gathered " + tweets.size() + " tweets");
for (Status t: tweets) {
System.out.println(t.getUser().getName() + ": " + t.getText()+ " " );
};
pg.setMaxId(lastID-1);
}
System.out.println(tweets.size());
}
The problem is that the result is only the same results, the algorithm takes only the first few tweets from the timeline and makes them X time, and the profile has a million of tweets.
Can someone tell me how can I solve this problem please?
Thanks
Here is a way to do :
ArrayList<Status> statuses = new ArrayList<>();
int pageno = 1;
while(true) {
try {
System.out.println("getting tweets");
int size = statuses.size(); // actual tweets count we got
Paging page = new Paging(pageno, 200);
statuses.addAll(twitter.getUserTimeline(screenName, page));
System.out.println("total got : " + statuses.size());
if (statuses.size() == size) { break; } // we did not get new tweets so we have done the job
pageno++;
sleep(1000); // 900 rqt / 15 mn <=> 1 rqt/s
}
catch (TwitterException e) {
System.out.println(e.getErrorMessage());
}
} // while(true)
And you need a sleep function to respect rate limit :
static void sleep(long ms) {
try { Thread.sleep(ms); }
catch(InterruptedException ex) { Thread.currentThread().interrupt(); }
}
Reference : https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline.html

pdfbox getcharacterbyarticle() rendering the vector for last page

I am trying to get text details like co-ordinates, width and height using the following code (took up this solution from here), but the output was only the text from the last page.
Code
public static void main( String[] args ) throws IOException {
PDDocument document = null;
String fileName = "apache.pdf"
PDFParser parser = new PDFParser(new FileInputStream(fileName));
parser.parse();
StringWriter outString = new StringWriter();
CustomPDFTextStripper stripper = new CustomPDFTextStripper();
stripper.writeText(parser.getPDDocument(), outString);
Vector<List<TextPosition>> vectorlistoftps = stripper.getCharactersByArticle();
for (int i = 0; i < vectorlistoftps.size(); i++) {
List<TextPosition> tplist = vectorlistoftps.get(i);
for (int j = 0; j < tplist.size(); j++) {
TextPosition text = tplist.get(j);
System.out.println(" String "
+ "[x: " + text.getXDirAdj() + ", y: "
+ text.getY() + ", height:" + text.getHeightDir()
+ ", space: " + text.getWidthOfSpace() + ", width: "
+ text.getWidthDirAdj() + ", yScale: " + text.getYScale() + "]"
+ text.getCharacter() +" Font "+ text.getFont().getBaseFont() + " PageNUm "+ (i+1));
}
}
}
CustomPDFTextStripper class:
class CustomPDFTextStripper extends PDFTextStripper
{
//Vector<Vector<List<TextPosition>>> data = new Vector<Vector<List<TextPosition>>>();
public CustomPDFTextStripper() throws IOException {
super();
}
public Vector<List<TextPosition>> getCharactersByArticle(){
// data.add(charactersByArticle);
return charactersByArticle;
}
}
I tried to add the vectors to a list, but when calling the stripper() it is iterating through all the pages and the last page details are stored in charactersByArticle vector and thus returning the same. How do I get info for all pages??
Temporary Fix:
Changed the main method to set the current page as end page and getting the text info. Not a good idea though.
for (int page = 0; page < pageCount; page++)
{
stripper.setStartPage(0);
stripper.setEndPage(page + 1);
stripper.writeText(parser.getPDDocument(), outString);
Vector vectorlistoftps = stripper.getCharactersByArticle();
PDPage thisPage = stripper.getCurrentPage();
for (int i = 0; i < vectorlistoftps.size(); i++) {
List<TextPosition> tplist = vectorlistoftps.get(i);
}
}

Failed to looping in a jtable in JCCD API

I have build code clone application, that using JCCD API that impelemnted ANTLR. To show the code clone, I am using a jtable. This is my screenshot Application : https://docs.google.com/file/d/0B_Rg--NnjJccMERpaTNidzR3cFE/edit?usp=sharing
Okey, from the following screenshot above, I was success to compare one file to another one file. The problem is when I am compare a file to two or more files. The tables just give me the last suspect of code clone.
But, in my netbeans output console, I was success that showed in this link : https://drive.google.com/file/d/0B_Rg--NnjJccWWdVTjdZc1R1bWc/edit?usp=sharing
How can I showed the right output console one to more files to my jTable ?
This is My code :
public static void printSimilarityGroups(final SimilarityGroupManager groupContainer) {
SimilarityGroup[] simGroups = groupContainer.getSimilarityGroups(); // output similarity groups
DefaultTableModel model = (DefaultTableModel) Main_Menu.jTable1.getModel();
model.setRowCount(0);
List<final_tugas_akhir.Report> theListData = new ArrayList<Report>();
if (null == simGroups) {
simGroups = new SimilarityGroup[0];
}
if ((null != simGroups) && (0 < simGroups.length)) {
for (int i = 0; i < simGroups.length; i++) {
final ASourceUnit[] nodes = simGroups[i].getNodes();
System.out.println("");
System.out.println("Similarity Group " + simGroups[i].getGroupId());
for (int j = 0; j < nodes.length; j++) {
final SourceUnitPosistion minPos = getFirstNodePosition((ANode) nodes[j]);
final SourceUnitPosistion maxPos = getLastNodePosition((ANode) nodes[j]);
ANode fileNode = (ANode) nodes[j];
while (fileNode.getTipe() != TipeNode.FILE.getTipe()) {
fileNode = fileNode.getParent();
}
final_tugas_akhir.Report theResult = new final_tugas_akhir.Report(); //final_tugas_akhir.Report() is a class that contain getter and setter
//Mixing the Line
StringBuilder sb = new StringBuilder();
StringBuilder append = sb.append(minPos.getBaris()).append("."); // get the row
sb.append(minPos.getKarakter()).append(" - "); //get Character
StringBuilder append1 = sb.append(maxPos.getBaris()).append(".");// get row
sb.append(maxPos.getKarakter()); get the character
theResult.setSimiliaritygroup(simGroups[i].getGroupId()); //Similiarity Group
theResult.setId(nodes[j].getId()); //setter similiarity id on token
theResult.setIndikasi(nodes[j].getText()); // setter Kind of Similairity
theResult.setFileutama(fileNode.getText()); //Files name
theResult.setLine(sb.toString());
theListData.add(theResult);
}
}
for (Report report : theListData) {
//test for the console
System.out.print(report.getSimiliaritygroup() + " ");
System.out.print(report.getId() + " ");
System.out.print(report.getIndikasi() + " ");
System.out.print(report.getFileutama() + " ");
System.out.print(report.getLine() + "\n");
//for table that failed
model.addRow(new Object[]{
report.getSimiliaritygroup(),
report.getId(),
report.getIndikasi(),
report.getFileutama(),
report.getLine()});
}
} else {
System.out.println("No similar nodes found.");
}
}
Thank you so much...

Categories

Resources