3
votes

I'm using Titanium SDK 3.4.0 GA, developing an Android app that load remote images from my web server to an ImageView.

The problem comes when the device lost connectivity during the load of that images, so, what I need is a way to catch that error (timeout, 404...) and set an "imageNotAvailable". I'm using Network Link Conditioner for MacOSX to reproduce that scenario, with low latency, lost of packets...

To prove this I use the following code in my test.js (Alloy Controller) and a simple view with an ImageView with id='imageView' in my test.xml.

Sometimes, throws an exception:

TiDownloadManager: (pool-4-thread-1) [45929,118581] Exception downloading http://...

but not always (remote connection timeout seems infinite), anyway with this exception and without this I can't catch this (probably due to the asynchronous request) nor fires the ERROR event.

function imageNotAvailable(e)
{       
    Ti.API.info('Error loading image:'+JSON.stringify(e));
    $.imageView.image = "/imageNotAvailable.png";
}

function onLoad(e)
{
    Ti.API.info('Image Loaded:'+JSON.stringify(e));
}

function setImageAndroid(image)
{
    try{
        $.imageView.image = 'http://....';
    }catch(e){
        $.imageView.fireEvent("error");
    }

    $.imageView.addEventListener("error", imageNotAvailable);
    $.imageView.addEventListener("load", onLoad);

}

Excuse my bad English! Thanks!

2

2 Answers

0
votes

Have you tried adding your event listeners before setting the imageView's image property?

0
votes

i can suggest a way around using http request

create a function in some library class which accepts the url that you are supposed to hit

Connection.getImage = function(link){
var xhr = Titanium.Network.createHTTPClient({
            onload : function(e) {
                var responseResult = this.responseText;
                callback(responseResult);
            },
            // function called when an error occurs, including a timeout
            onerror : function(e) {
                callback("fail");
                // Ti.API.info('IN ERROR ' + e.error);
            },
         timeout : 5000
        });

    xhr.open("GET", link);
xhr.send();
};

// ps you will receive a blob in response which you can attach to imageView.blob property , an it would suggest using a default image which will act as placeholder until you get the success response.