We are about to switch to a new forum software. Until then we have removed the registration on this forum.
It seems like you can only define the content from the XML at the certain time in void setup.
I am trying to load headlines from say for example bbc.co.uk. My code loads the XML, and then in void draw, it displays the headline by scrolling from right to left. That works all good.
But if my first paragraph is true, that means that in void draw, it will run out of headlines to print, and it will just repeat the content due to loadXML being load only once. Is that right?
Is there anyway to check it from time to time?
// Example 17-3: Scrolling headlines
// An array of news headlines
String[] titles; /*= {
"Processing downloads break downloading record." , // Multiple Strings are stored in an array.
"New study shows computer programming lowers cholesterol." ,
};*/
PFont f; // Global font variable
float x; // Horizontal location
int index = 0;
void setup() {
size(400,200);
f = createFont( "Arial" ,16,true);
// Initialize headline offscreen
x = width;
String url = "http://www.worldpress.org/feeds/topstories.xml";
XML rss = loadXML(url);
// Get title of each element
XML[] titleXMLElements = rss.getChildren("channel/item/title");
titles = new String[titleXMLElements.length];
for (int i = 0; i < titleXMLElements.length; i++) {
String title = titleXMLElements[i].getContent();
// Store title in array for later use
titles[i] = title;
}
}
void draw() {
background(255);
fill (0);
// Display headline at x location
textFont(f,16);
textAlign (LEFT);
text(titles[index],x, 20); // A specific String from the array is displayed according to the value of the “index” variable.
// Decrement x
x = x - 1;
// If x is less than the negative width,
// then it is off the screen
float w = textWidth(titles[index]); // textWidth() is used to calculate the width of the current String.
if (x < -w) {
x = width;
index = (index + 1) % titles.length; // “index"is incremented when the current String has left the screen in order to display a new String.
}
}
Answers
Use millis() to determine when a certain amount of time has passed. When it has, re-run your XML loading code to see if there is new data:
Alternatively, you might consider spawning a second thread that does this if the XML load code causes your sketch to lag/freeze every 10 seconds... That is actually a better solution...
https://forum.Processing.org/two/discussion/18591/how-to-call-thread-functionname-in-draw#Item_6