We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProcessing DevelopmentLibraries,  Tool Development › requestStrings function
Page Index Toggle Pages: 1
requestStrings function (Read 814 times)
requestStrings function
Nov 25th, 2008, 9:25pm
 
This is a blatant ripoff of the requestImage function.
I don't know how useful this is for others, but I found a use for it. This allows you to show a loading screen while large text files are downloaded.
There is a problem, though; you have to know the number of strings in the file.
Does anyone know of a better way?

PS: expand(array) returns a new array, eliminating the reference to the target.

Edit: Sorry, I should have put this in Core dev.

Quote:
//
// Usage==========================================

int stringcount=50;
String[] lines = new String[stringcount];
lines = requestStrings("file.txt", "default text", stringcount);

// Elsewhere...
if (!lines[0].equals("default text") && !lines[0].equals("empty")) {
 //do something
}

// ==============================================
//


String[] requestStrings(String filename, int len) {
 return requestStrings(filename, null, len);
}

String[] requestStrings(String filename, String filler, int len) {
 String[] vessel = new String[len];
 vessel[0] = "empty";
 
 if (filler != null) {
   vessel[0] = filler;
 }
 
 AsyncStringLoader asl =
   new AsyncStringLoader(filename, vessel);
 asl.start();
 return vessel;
}


/**
* Based on requestImage routine. Allows larger text files to be loaded
* in the same way as images.
*/
int requestTextFileMax = 4;
volatile int requestTextFileCount;

class AsyncStringLoader extends Thread {
 String filename;
 String[] shell;

 AsyncStringLoader(String filename, String[] vessel) {
   this.filename = filename;
   shell = vessel;
 }

 void run() {
   while (requestTextFileCount == requestTextFileMax) {
     try {
       Thread.sleep(10);
     } catch (InterruptedException e) { }
   }
   requestTextFileCount++;

   String[] actual = loadStrings(filename);

   // An error message should have already printed
   if (actual != null) {
     println(actual.length);
     //shell = (String[])expand(shell, actual.length);
     //expand(shell, actual.length);
     println(shell.length);
     if (shell.length == actual.length) {
       arrayCopy(actual, shell);
     } else {
       println("Array size does not match");
     }
     //println("done");
     //println(lines);
   }
   requestTextFileCount--;
 }
}

Page Index Toggle Pages: 1