Your problem is that code is not synchronized.
You need to use methods wait()
and notify()
, about like below:
public synchronized void run() {
try {
contacts.removeAllElements();
//...
readComplete = true;
this.notify();
} catch (Exception e) {
}
}
//Return contacts loaded into vector list
public synchronized // <-- note sync'd here
ContactVector getLoadedContacts() {
while(!readComplete){
this.wait();
}
return contacts;
}
This is pretty basic stuff, consider studying Java tutorials on concurrency.
If possible, look for tutorials for Java versions earlier than Java 5, otherwise explanation of things you can use in Java ME (limited to Java 1.3 as of now) will be "mixed" with modern features, making it harder to learn parts that are relevant for you.
An example tutorial that worked that way for me was by Jacob Jenkov here, chapters from "Introduction..." to "Slipped Conditions" inclusive. Note further chapters ("Locks" and the rest) aren't bad either but these heavily rely on features introduced since Java 5 (JSRs 133 / 166 - JMM and concurrency utilities).
Couple obsevations on the code not related to the bug explained above.
Since your code is quite complicated, consider adding log messages to make it easier to debug (as explained eg here). In particular I'd strongly to log things like exception in catch block (search web for something like _Java don't swallow exceptions" if you're interested why), as well as whether
lists
is null and if it isn't, what is its size and whetherclist
,cenum
andc
are null or not.Consider making your code easier to read and modify by extracting into separate methods (as explained here) code that is in your snippet within
for
andwhile
loops.Note that since code in
getContactVector()
might take a long time to run, you better avoid calling it from UI thread. If you're interested to understand why is that and how to do it right, check the tutorial "Networking, User Experience, and Threads" referred to in lcdui tag wiki.