Well, first of all, this will not work:
public String jsonResult(String url){
this.url = url;
this.start();
return response;
}
Calling start()
will cause run()
to be called on a background thread (that's good). However, immediately after you start the background thread, you return the response
member variable. That won't work, because the run()
method hasn't had time to actually assign the response
variable.
What you need to do is assign the response
variable at the end of the run()
method, and then notify the UI on the main/UI thread, to let it update the user interface. Something like this:
if (code == HttpConnection.HTTP_OK) {
in = conn.openInputStream();
byte[] buffer = IOUtilities.streamToBytes(in);
this.response = new String(buffer,"UTF-8");
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
// this code is run on the main/UI thread
if (observer != null) {
observer.onResponseReceived(this.response);
}
}
});
where you add a new observer interface
public interface JsonObserver {
public void onResponseReceived(String response);
}
and then you can let your MainScreen
implement that interface:
public class MyScreen extends MainScreen implements JsonObserver {
public MyScreen()
{
connectJson.setObserver(this);
// start the json request
connectJson.jsonResult("http://musicbrainz.org/ws/2/release/59211ea4-ffd2-4ad9-9a4e-941d3148024a?inc=artist-credits+labels+d...");
}
public void onResponseReceived(String response) {
System.out.println("000000000000000000000000000000000"+response);
// TODO: create or update your ListField here!!!
}
Of course, you'll need a new member and method in the ConnectJson
class, too:
private JsonObserver observer;
public void setObserver(JsonObserver o) {
observer = o;
}
Note: it also might be better, for thread safety, to change your response
member variable to a simple local final
variable. I can't know all the ways that you plan on using it, but if it's just a way to hold onto the JSON response, you probably don't need a member variable. Try this instead (inside of run()
):
final String response = new String(buffer,"UTF-8");
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
observer.onResponseReceived(response);