Problem JSON.parse(xhr.responseText) in Android

You must Login before you can answer or comment on any questions.

Hi,

Titanium SDK: 2.1.0 GA IOS and Android

I have a trouble with:

exports.isOnline = function() {
 
    var xhr = Ti.Network.createHTTPClient();
 
    xhr.setTimeout(15000);
    xhr.open('GET', urlServer + 'manager/isOnline', false);
    xhr.send();
 
    xhr.onerror = function(e) {
        alert('Ops, ocorreu um erro na conexão com o servidor.');   
    };
 
    var jsonObject = JSON.parse(xhr.responseText);
    if (jsonObject != null && jsonObject.isOnline === true) {
        Ti.API.info('Server: On!');
        return true;
    } else {
        Ti.API.info('Server: Off!');
        return false;
    }
};
Webserver echo:
{"isOnline":false}

Ps: In IOS this code works fine.

2 Answers

You're trying to treat the HTTPClient as if it is synchronous. It is asynchronous. You need to provide an onload function, which is called after the response is received.

exports.isOnline = function() {
 
    var xhr = Ti.Network.createHTTPClient();
 
    xhr.setTimeout(15000);
    xhr.open('GET', urlServer + 'manager/isOnline', false);
    xhr.send();
 
    xhr.onerror = function(e) {
        alert('Ops, ocorreu um erro na conexão com o servidor.');   
    };
 
    xhr.onload = function ()
    {
        var jsonObject = JSON.parse(xhr.responseText);
        if (jsonObject != null && jsonObject.isOnline === true) {
            Ti.API.info('Server: On!');
            //return true;
            // do something like fire an event
        } else {
            Ti.API.info('Server: Off!');
            //return false;
            // do something like fire an event
        }
    }
 
};
Notice that I suggest you fire an event or something. It's not going to be as simple as calling a function like isOnline() and getting back a boolean true/false result. Your app will have to call the function and then react to the response when it comes back, either via a callback function that you could pass to isOnline, or via a synthetic event that your code could fire on a view.

Either way, it takes a whole different mindset to deal with the asynchronous nature of the network requests.

— answered 2 years ago by Jason Priebe
answer permalink
4 Comments
  • i needed something like a simple function for test response from webserver. I cant imagine how can i do this with fireevent.

    — commented 2 years ago by Philipe Steiff

  • Like I said, it takes a whole different mindset to get used to the asynchronous requests. You can't change the fact that they're asynchronous, so don't waste time trying to force it into a synchronous model. Your code won't work the way you are doing it.

    Here's a rough idea of how you could do things with a callback:

    • open your main app window, but don't present the full user interface
    • call isOnline() and pass it a callback function
    • in the xhr.onload function, you can parse the JSON and then call the callback function, passing it the result
    • the callback function looks at the response and acts appropriately (maybe if the test is true, it adds the views to the main window; if it's false, it presents an error dialog; I can't tell you what your app needs to do here)

    That's the general way you have to handle these things. You're not going to be able to write a network function that you can simply call and look at the response. This is exactly like writing AJAX code if you've ever done that -- asynchronous requests is a core concept.

    — commented 2 years ago by Jason Priebe

  • but if he doesn't wan't to use event firing, xhr.onload or xhr.onreadystatechange should work fine enough to get the json string and be able to parse it

    — commented 2 years ago by Moritz Roessler

  • Show 1 more comment

Ops, i forgot the error message:

07-18 16:44:11.009: E/TiJSError(2612): (main) [64,623] ----- Titanium Javascript Runtime Error -----
07-18 16:44:11.009: E/TiJSError(2612): (main) [0,623] - In undefined:0,0
07-18 16:44:11.009: E/TiJSError(2612): (main) [0,623] - Message: Uncaught SyntaxError: Unexpected end of input
07-18 16:44:11.009: E/TiJSError(2612): (main) [0,623] - Source:

Your Answer

Think you can help? Login to answer this question!