Is there a way to check loadXML periodically?

edited May 2017 in Questions about Code

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

  • edited May 2017

    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:

    int time;
    
    void setup(){
      size(...);
      loadData(); // Loads your XML, parses it, ect.
      time = millis() + 10000; // do it again in 10 seconds.
    }
    
    void draw(){
      if( millis() > time ){
        loadDatat();
        time = millis() + 10000;
      }
     // ...
    }
    

    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...

Sign In or Register to comment.