<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>aviyehuda.com</title>
	
	<link>http://www.aviyehuda.com</link>
	<description />
	<lastBuildDate>Sun, 07 Apr 2013 10:06:23 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.4.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/aviyehuda/feed" /><feedburner:info uri="aviyehuda/feed" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>jQuery Deferred – one step closer to desktop apps</title>
		<link>http://feedproxy.google.com/~r/aviyehuda/feed/~3/x4NzbNwnHOM/</link>
		<comments>http://www.aviyehuda.com/blog/2013/03/15/jquery-deferred-one-step-closer-to-desktop-apps/#comments</comments>
		<pubDate>Fri, 15 Mar 2013 19:19:59 +0000</pubDate>
		<dc:creator>Avi</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Web development]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[jquery_deferred]]></category>
		<category><![CDATA[Web_developing]]></category>

		<guid isPermaLink="false">http://www.aviyehuda.com/?p=2480</guid>
		<description><![CDATA[Every time I forget why I like jQuery, they keep reminding me. Not too long ago I came across jQuery deferred (even though it was added already in JQuery 1.5) and I immediately liked it. I feel this feature brings <a class="more-link" href="http://www.aviyehuda.com/blog/2013/03/15/jquery-deferred-one-step-closer-to-desktop-apps/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div style="float: left; padding-right: 10px"><img width="300px" src="http://blog.teamtreehouse.com/wp-content/uploads/2012/10/jquery.jpg" >
</div>
<div>
Every time I forget why I like jQuery, they keep reminding me.<br />
Not too long ago I came across <a href="http://api.jquery.com/category/deferred-object/">jQuery deferred</a> (even though it was added already in JQuery 1.5) and I immediately liked it. I feel this feature brings the web application development a bit closer to the desktop development.
</div>
<p><br/></p>
<p>Deferreds simply let you add multiple callback to long lasting operation calls like Ajax requests.</p>
<p><strong>Long lasting operations without JQuery Deferred</strong><br />
If you haven&#8217;t used deferreds, this is probably how you had done long lasting actions like ajax calls.</p>
<pre class="brush: jscript; title: ; notranslate">$.get(&quot;/myservice/x/1&quot;,function(data,status){alert ('example')})</pre>
<p>Long lasting operations like ajax require a callback function.<br />
In this case the callback is given as a parameter to the caller.</p>
<p>This is fine, but there is a way to add a callback separately from the call.</p>
<pre class="brush: jscript; title: ; notranslate">var myPromise = $.get(&quot;/myservice/x/1&quot;);

myPromise.done(function(data,status){alert ('ok')})
myPromise.fail(function(data,status){alert ('failed')})</pre>
<p><a target="_blank" href="http://jsfiddle.net/aviyehuda/heF7B/">Try it</a></p>
<p>This is actually the simplest example of using Deferreds.<br />
JQuery ajax methods (get,post,ajax&#8230;) return an object which you can add callback methods to it.</p>
<p><strong>Why is it better?</strong><br />
Simply because it lets you keep the logic of execution and the logic of the result separated. This makes a more readable and maintainable code.</p>
<p><strong>So what is a &#8216;Deferred&#8217;?</strong><br />
Deferred is an object which lets you add multiple callback methods to it.<br />
It also triggering events which determine the state of the call, using it will determine which callback methods will be triggered.</p>
<p>In the Ajax example above the 2 callbacks are &#8216;done&#8217; and &#8216;fail&#8217; which are triggered according to the state of the Ajax call.</p>
<p>This list shows which events will trigger which callbacks. </p>
<style>
.my_table td{
border: 1px solid #aaaaaa; 
font-size: 11px;
}
</style>
<table  cellpadding="3" cellspacing="1" class="my_table">
<tbody>
<tr>
<td>Callbacks&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Events&rarr;<br/>&nbsp;&nbsp;&darr;</td>
<td>
				deferred.always()</td>
<td>
				deferred.done()</td>
<td>
				deferred.fail()</td>
<td>
				deferred.progress()</td>
</tr>
<tr>
<td>
				deferred.notify()</td>
<td>
				&nbsp;</td>
<td>
				&nbsp;</td>
<td>
				&nbsp;</td>
<td bgcolor='#00FF00'>
				Triggered</td>
</tr>
<tr>
<td>
				deferred.notifyWith()</td>
<td>
				&nbsp;</td>
<td>
				&nbsp;</td>
<td>
				&nbsp;</td>
<td bgcolor='#00FF00'>
				Triggered</td>
</tr>
<tr>
<td>
				deferred.reject()</td>
<td bgcolor='#00FF00'>
				Triggered</td>
<td>
				&nbsp;</td>
<td bgcolor='#00FF00'>
				Triggered</td>
<td>
				&nbsp;</td>
</tr>
<tr>
<td>
				deferred.rejectWith()</td>
<td bgcolor='#00FF00'>
				Triggered</td>
<td>
				&nbsp;</td>
<td bgcolor='#00FF00'>
				Triggered</td>
<td>
				&nbsp;</td>
</tr>
<tr>
<td>
				deferred.resolve()</td>
<td bgcolor='#00FF00'>
				Triggered</td>
<td bgcolor='#00FF00'>
				Triggered</td>
<td>
				&nbsp;</td>
<td>
				&nbsp;</td>
</tr>
<tr>
<td>
				deferred.resolveWith()</td>
<td bgcolor='#00FF00'>
				Triggered</td>
<td bgcolor='#00FF00'>
				Triggered</td>
<td>
				&nbsp;</td>
<td>
				&nbsp;</td>
</tr>
</tbody>
</table>
<p><strong>What is a &#8216;Promise&#8217;?</strong><br />
A Promise is an object which is given from the Deferred and may be used just to add callbacks.</p>
<p>The 2 objects, Deferred and Promise, give us the separation in the logic of the caller and the logic of the result.</p>
<p>For example, in the ajax calls of JQuery, the ajax call creates a Deferred and also a Promise from that Deferred. The Deferred is used to trigger events and the Promise is returned to the user so he will add callback functions to it.</p>
<p><strong>Create your own Deferreds functions</strong><br />
You also can use Deferreds in your function much like the ajax functions are using them.</p>
<p>These are the steps:<br />
1. Create a Deffered inside your function.<br />
2. Use the Deffered to trigger events.<br />
3. Return the Promise object. </p>
<p>See this simple example:</p>
<pre class="brush: jscript; title: ; notranslate">myLongLastingOperation = function(time) {
  var myDeferred = $.Deferred();
  setTimeout(myDeferred.resolve, time);
  return myDeferred.promise();
}

myPromise = myLongLastingOperation(1000);
myPromise.done(function(){alert('ok')})
myPromise.fail(function(){alert('failed')})</pre>
<p><a target="_blank" href="http://jsfiddle.net/aviyehuda/4wfRF/">Try it</a></p>
<p>In the example above I have created a function similar to the what ajax function is doing.<br />
I have created a Deferred, used that Deferred to trigger an event by using the resovle() function once the operation was done, and returned the Promise which I created from that Deferred.<br />
The returned promise is then used for adding callbacks. </p>
<p><strong>Progress</strong><br />
resolve() and reject() are both events that determine the status of the result of the operation.<br />
But there is another event you can trigger &#8211; notify().<br />
This event which was added in version 1.7 can be triggered if you have a process and you want to trigger a callback while the process is still running.  </p>
<pre class="brush: jscript; title: ; notranslate">myLongLastingOperation = function(time,numOfCount) {
 var  myDeferred = $.Deferred();
   
   function wait(counter){
        if(counter&lt;numOfCount){
            myDeferred.notify();
            setTimeout(function(){wait(counter+1)}, time);   
        }   
        else{
             myDeferred.resolve();
        }
    }
   wait(0); 
  return myDeferred.promise();
}

myPromise = myLongLastingOperation(100, 3);
myPromise.progress(function(){document.write('tick')});
myPromise.done(function(){document.write('done')});</pre>
<p><a target="_blank" href="http://jsbin.com/arefop/1/edit">Try it</a></p>
<p><strong>Not impressed yet? Meet &#8216;when&#8217;</strong><br />
We saw that you can add multiple callbacks to Deferreds and Promises.<br />
&#8216;when&#8217; lets you do the same thing but it can do it for multiple Deferreds all at once. </p>
<pre class="brush: jscript; title: ; notranslate">myLongLastingOperation = function(time) {
 var  myDeferred = $.Deferred();
 setTimeout(function(){myDeferred.resolve();}, time);
 return myDeferred.promise();
}


myPromise = $.when( 
    myLongLastingOperation(500),
    myLongLastingOperation(1700));

myPromise.done(function(){document.write('done')});</pre>
<p><a target="_blank" href="http://jsfiddle.net/aviyehuda/Xh447/">Try it</a></p>
<p>In this case the done callback will be triggered only when the 2 processes are resolved.<br />
This gives you the ability to synchronize between many long lasting processes, which can be useful for so many things.<br />
For example, if you are loading many sources and you wish to do something when they are all done.</p>
<p><strong>Changing the result with &#8216;then&#8217;</strong><br />
I mentioned that you can&#8217;t trigger events on a Promise, you can only add events to a Promise.<br />
However, you still have a way to control the result in another way; by adding filters to the Promise which will be able to alter the response from the caller.<br />
Since jQuery 1.8 this is done using the &#8216;<a href="http://api.jquery.com/deferred.then/" target="_blank">then</a>&#8216; command:</p>
<pre class="brush: jscript; title: ; notranslate">var myPromise = $.get('non_exiting.php');

myPromise = myPromise.then(
    function(){return $.Deferred().resolve(&quot;ok&quot;)},
    function(){return $.Deferred().resolve(&quot;ajax failed but still we pass&quot;)});

myPromise.done(function(message){document.write('done: '+message);});
myPromise.fail(function(message){document.write('error: '+message);});</pre>
<p><a href="http://jsfiddle.net/aviyehuda/KF2wU/" target="_blank">Try it</a></p>
<p>This example shows that even though the deferred(the ajax) failed, the filter changed the result to resolve, causing the &#8216;done&#8217; callback to be triggered instead of &#8216;fail&#8217;.<br />
Notice that &#8216;then&#8217; returns also a promise, this makes it a chainable command, which means that you can chain a more than one filter one after the other.</p>
<p><strong>*Notice</strong>, before version 1.8 you would do this using the <a href="http://api.jquery.com/deferred.pipe/"><del >pipe</del></a> command, but since 1.8 it is done using &#8216;<a href="http://api.jquery.com/deferred.then/">then</a>&#8216;.<br />
&#8216;then&#8217; was originally added in version 1.5 as a callback which is triggered on every event.<br />
But since version 1.8 it changed it&#8217;s purpose to be a filtering chainable method which can effect the state of the result.<br />
This is why you can still see examples on the web that do it the old way.</p>
<p><strong>Adding a callbacks after event was triggered</strong><br />
You should know that you can add callback functions to a promise even if the Deferred was already resolved or failed.<br />
This means that if you add a callback method to an ajax call for example, that already returned, the callback would immediately be triggered.</p>
<p>This small and seemingly unimportant feature is actually quite useful, because you don&#8217;t have to worry that the Deferred is finished when adding callbacks. More over, it lets you add many callbacks whenever you like and by so, reuse deferreds.<br />
A good example for this use would be a cache of ajax calls, this is infact something I have implemented in my workplace(<a href="http://www.convertro.com" target="_blank">convertro.com</a>) quite successfully.</p>
<p><a href="http://api.jquery.com/category/deferred-object/">jQuery Deferred</a></p>
<img src="http://feeds.feedburner.com/~r/aviyehuda/feed/~4/x4NzbNwnHOM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.aviyehuda.com/blog/2013/03/15/jquery-deferred-one-step-closer-to-desktop-apps/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.aviyehuda.com/blog/2013/03/15/jquery-deferred-one-step-closer-to-desktop-apps/</feedburner:origLink></item>
		<item>
		<title>JavaScript encapsulation &amp; the module pattern</title>
		<link>http://feedproxy.google.com/~r/aviyehuda/feed/~3/z0TRifbiMFM/</link>
		<comments>http://www.aviyehuda.com/blog/2013/01/12/javascript-encapsulation-the-module-pattern-for-beginners/#comments</comments>
		<pubDate>Sat, 12 Jan 2013 17:50:55 +0000</pubDate>
		<dc:creator>Avi</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Web development]]></category>
		<category><![CDATA[module_pattern]]></category>
		<category><![CDATA[Web_developing]]></category>

		<guid isPermaLink="false">http://www.aviyehuda.com/?p=2397</guid>
		<description><![CDATA[Encapsulation is one of the key features of object oriented programming languages. In languages like Java, it is very straight forward concept to implement. Since I know JavaScript is considered an OO language, I decided to try to understand once <a class="more-link" href="http://www.aviyehuda.com/blog/2013/01/12/javascript-encapsulation-the-module-pattern-for-beginners/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><img src="images/js_encp.jpg" style="float: left; padding: 10px"><a href="http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)">Encapsulation</a> is one of the key features of object oriented programming languages.<br />
In languages like Java, it is very straight forward concept to implement.</p>
<p>Since I know JavaScript is considered an OO language, I decided to try to understand once and for all how to implement encapsulation in JavaScript correctly.</p>
<p><br/><br />
Let&#8217;s say we have a function with one private field and one public field:</p>
<pre class="brush: jscript; title: ; notranslate">
function f1() {
	var x=3; //private	
	this.y=4; //public
}

//alert(x); // error - x is undefined
//alert(y);// error - y is undefined
alert(f1.x); //alert undefined
alert(f1.y); //alert undefined
//alert(f1().x); //error - f1() does not return an object with property x
//alert(f1().y); //error - f1() does not return an object with property y
</pre>
<p><a target=_blank href="http://jsfiddle.net/aviyehuda/crA5E/" >Try It</a></p>
<p>The fields are of course undefined since we need to call f1() in order for them to have values.</p>
<p>Now let&#8217;s create an object from that function:</p>
<pre class="brush: jscript; title: ; notranslate">
var i1 = new f1();

//alert(x); // error 
//alert(y);// error 
alert(i1.x);//alert undefined since it is private
alert(i1.y); //alert 4
</pre>
<p><a target=_blank href="http://jsfiddle.net/aviyehuda/Cb2Eh/" >Try It</a></p>
<p>After instancing, x and y both have values, but of course, only y is public.</p>
<p>Now lets encapsulate field x.</p>
<pre class="brush: jscript; title: ; notranslate">
function f1() {
	var x=3; //private	
	this.y=4; //public

	this.getX = function(){
		return x;
	}
}

var i1 = new f1();

//alert(x); //error
alert(i1.x); //alert undefined
alert(i1.getX()); //alert 3
</pre>
<p><a target=_blank href="http://jsfiddle.net/aviyehuda/p6mYD/" >Try It</a></p>
<p>This is the most basic encapsulation and it works.<br />
But this approach has a problem, f1() is in fact a kind of constructor. Whenever an instance will be created than the getter method will also be created.<br />
This approach is not the preferred way to create methods in JavaScript.</p>
<p>The preferred approach in JavaScript is to create the methods attached to the prototype. In this way they will only be created once.</p>
<pre class="brush: jscript; title: ; notranslate">
var f1 = function(){
	var x=3; //private	
	this.y=4; //public
}

f1.prototype.getY = function(){
	return y;
}

/* error
f1.prototype.getX = function(){
	return x; //x is not a public field
}
*/
</pre>
<p>But this approach also has a problem, we cannot use it for private fields.</p>
<p>Let&#8217;s consider using a module</p>
<pre class="brush: jscript; title: ; notranslate">
f1 = (function (){
	var x=3;

	var module = function (){
		this.getX = function(){
			return x;
		}
	}

	return module;
})();

var i1 = new f1();
alert(i1.x); //undefined
alert(i1.getX()); //3
</pre>
<p><a target=_blank href="http://jsfiddle.net/aviyehuda/fMsKp/" >Try It</a></p>
<p>There is a function which creates a module with the getter.<br />
But here we have the same problem as the first example, getX() is created for every instance.</p>
<p>The solution is in fact a combination of the previous 2 examples:</p>
<pre class="brush: jscript; title: ; notranslate">
f1 = (function (){
	var x=3;

	var module = function (){}
	
	module.prototype.getX = function(){
		return x;
	}

	return module;
})();

var i1 = new f1();

//alert(x); undefined
alert(f1.x); //undefined
alert(i1.getX()); //3
</pre>
<p><a target=_blank href="http://jsfiddle.net/aviyehuda/nNQsj/" >Try It</a></p>
<p>Here you have a strict encapsulation which is also efficient in memory.</p>
<img src="http://feeds.feedburner.com/~r/aviyehuda/feed/~4/z0TRifbiMFM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.aviyehuda.com/blog/2013/01/12/javascript-encapsulation-the-module-pattern-for-beginners/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://www.aviyehuda.com/blog/2013/01/12/javascript-encapsulation-the-module-pattern-for-beginners/</feedburner:origLink></item>
		<item>
		<title>Chrome extension: Right-To-Left display in Google Calendar</title>
		<link>http://feedproxy.google.com/~r/aviyehuda/feed/~3/LaCjMqIF3HY/</link>
		<comments>http://www.aviyehuda.com/blog/2013/01/02/chrome-extension-right-to-left-display-in-google-calendar/#comments</comments>
		<pubDate>Wed, 02 Jan 2013 09:21:46 +0000</pubDate>
		<dc:creator>Avi</dc:creator>
				<category><![CDATA[Chrome extension]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[Chrome_extensions]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[open_source]]></category>
		<category><![CDATA[Web_developing]]></category>

		<guid isPermaLink="false">http://www.aviyehuda.com/?p=2401</guid>
		<description><![CDATA[I love Google Calendar, but one thing bothered me about it; sometimes I add events with Hebrew and sometimes even a mixture of both English and Hebrew. Google Calendar doesn&#8217;t support it, when creating/editing events, it displays it in Left-To-Right <a class="more-link" href="http://www.aviyehuda.com/blog/2013/01/02/chrome-extension-right-to-left-display-in-google-calendar/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I love Google Calendar, but one thing bothered me about it; sometimes I add events with Hebrew and sometimes even a mixture of both English and Hebrew.<br />
Google Calendar doesn&#8217;t support it, when creating/editing events, it displays it in Left-To-Right order.</p>
<p>That&#8217;s why I have created this Chrome Extension which works great for Hebrew and Arabic.</p>
<p><center><a href="https://chrome.google.com/webstore/detail/righttoleftcalender/hcpipiahmegbmbngagjcojhbpacmjajm?hl=en-US"><img alt='Github' src='https://developers.google.com/chrome/web-store/images/branding/ChromeWebStore_Badge_v2_206x58.png'/></a></center><br />
&nbsp;<a href="https://github.com/aviyehuda/RightToLeftGoogleCalendar"><img alt='Github' width="40px" src='http://fukamachi.github.com/images/github-icon.jpg'/> View on Github</a><br />
&nbsp;<a href="https://github.com/aviyehuda/RightToLeftGoogleCalendar/archive/master.zip"  ><img src="/ficons/zip.gif" alt="zip">&nbsp;Download Source code</a></p>
<p><center><br />
<img src="https://lh3.googleusercontent.com/AbkFBXj-rPl49BgpJsKRGG329MBaBFXw0MO8_F_NwLt704Xm7d5KaoCIZ9ylqlKqgfbIiGLQQQ=s640-h400-e365-rw" style="border: solid 1px"><br />
</center></p>
<p><em>*Google Calendar is a trademark of Google Inc.</em></p>
<img src="http://feeds.feedburner.com/~r/aviyehuda/feed/~4/LaCjMqIF3HY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.aviyehuda.com/blog/2013/01/02/chrome-extension-right-to-left-display-in-google-calendar/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.aviyehuda.com/blog/2013/01/02/chrome-extension-right-to-left-display-in-google-calendar/</feedburner:origLink></item>
		<item>
		<title>Web development for mobile</title>
		<link>http://feedproxy.google.com/~r/aviyehuda/feed/~3/oONtWyrG7Gw/</link>
		<comments>http://www.aviyehuda.com/blog/2012/07/25/web-development-for-mobile/#comments</comments>
		<pubDate>Wed, 25 Jul 2012 17:53:00 +0000</pubDate>
		<dc:creator>Avi</dc:creator>
				<category><![CDATA[ClientSide]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Web development]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[phonegap]]></category>
		<category><![CDATA[presentation]]></category>
		<category><![CDATA[sencha]]></category>
		<category><![CDATA[titanum]]></category>

		<guid isPermaLink="false">http://www.aviyehuda.com/?p=2342</guid>
		<description><![CDATA[I gave a short lecture at work about web development for mobile. It is an overview of the current trends and technologies with a few suggestions. Hope you enjoy it. Here is the presentation: Link to prezi]]></description>
			<content:encoded><![CDATA[<p>I gave a short lecture at work about web development for mobile.<br />
It is an overview of the current trends and technologies with a few suggestions.<br />
Hope you enjoy it.</p>
<p>Here is the presentation:</p>
<div class="prezi-player">
<style type="text/css" media="screen">.prezi-player { width: 550px; } .prezi-player-links { text-align: center; }</style>
<p><object id="prezi_yqcrdsqpjanm" name="prezi_yqcrdsqpjanm" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="550" height="400"><param name="movie" value="http://prezi.com/bin/preziloader.swf"/><param name="allowfullscreen" value="true"/><param name="allowFullScreenInteractive" value="true"/><param name="allowscriptaccess" value="always"/><param name="bgcolor" value="#ffffff"/><param name="flashvars" value="prezi_id=yqcrdsqpjanm&amp;lock_to_path=0&amp;color=ffffff&amp;autoplay=no&amp;autohide_ctrls=0"/><embed id="preziEmbed_yqcrdsqpjanm" name="preziEmbed_yqcrdsqpjanm" src="http://prezi.com/bin/preziloader.swf" type="application/x-shockwave-flash" allowfullscreen="true" allowFullScreenInteractive="true" allowscriptaccess="always" width="550" height="400" bgcolor="#ffffff" flashvars="prezi_id=yqcrdsqpjanm&amp;lock_to_path=0&amp;color=ffffff&amp;autoplay=no&amp;autohide_ctrls=0"></embed></object>
</div>
<h2><a href="http://prezi.com/yqcrdsqpjanm/mobilewebdevlopment/">Link to prezi</a></h2>
<img src="http://feeds.feedburner.com/~r/aviyehuda/feed/~4/oONtWyrG7Gw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.aviyehuda.com/blog/2012/07/25/web-development-for-mobile/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.aviyehuda.com/blog/2012/07/25/web-development-for-mobile/</feedburner:origLink></item>
		<item>
		<title>How to change pages in a web application in the age of HTML5</title>
		<link>http://feedproxy.google.com/~r/aviyehuda/feed/~3/Sy-Ra2JzLOQ/</link>
		<comments>http://www.aviyehuda.com/blog/2012/04/29/how-to-change-pages-in-a-web-application-in-the-age-of-html5/#comments</comments>
		<pubDate>Sun, 29 Apr 2012 10:41:45 +0000</pubDate>
		<dc:creator>Avi</dc:creator>
				<category><![CDATA[HTML5]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://www.aviyehuda.com/?p=2202</guid>
		<description><![CDATA[More and more web sites stop to use the old way of request-response page switches, where each page switch refreshes the entire page in the browser. Instead they refresh just the data and the page itself is not reloaded. This <a class="more-link" href="http://www.aviyehuda.com/blog/2012/04/29/how-to-change-pages-in-a-web-application-in-the-age-of-html5/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>More and more web sites stop to use the old way of request-response page switches, where each page switch refreshes the entire page in the browser.<br />
Instead they refresh just the data and the page itself is not reloaded.<br />
This way has better for performance and it also makes a much smoother user experience.</p>
<p>You can see a great example in <a href="https://github.com/joyent/node">github</a> where you click on one of the files.</p>
<p>In this post I am going to explain how this is achieved step by step.</p>
<h2><a target="_blank" href="http://aviyehuda.com/pageSwitchTest/">My Demo</a></h2>
<p><br/><strong>Requirements:</strong><br />
For some reason, almost all of the examples I saw on the internet about this used jquery in one way or another.<br />
This post is NOT using any third-party libraries except for history.js script <a href="https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history#Browser_compatibility">for browsers which do not support the history.pushState feature</a>. I took this script from <a href="https://github.com/fortes/history.js">github</a>.</p>
<p><br/><strong>Step 1 &#8211; handle links</strong><br />
We want that pressing a link will trigger a JavaScript function.<br />
You can do that in many ways.<br />
I have done it like this:</p>
<pre class="brush: jscript; title: ; notranslate">
	var elements = document.getElementsByTagName('a');
	var address;
	for(var i=0; i&lt;elements.length;i++){
		element=elements[i];
		address=element.getAttribute('href');
		if(address.substring(0,2)==&quot;./&quot;){ //inner links only
			element.setAttribute('onclick','goto(&quot;'+address+'&quot;,event)');
		}
	}
</pre>
<p>It will go over all the links in the page and will attach a call to function goto(), but it will do it just for the links which points to inner pages.<br />
The goto() function gets the address of the page and the click event.<br />
In this way you write you link tags as usual.</p>
<p><br/><strong>Step 2 &#8211; prevent page redirection</strong><br />
We want that pressing on a link will not cause the web page to be redirected, so we need prevent the default behavior of the click event on the link.<br />
This is how it is done:</p>
<pre class="brush: jscript; title: ; notranslate">
theEvent.preventDefault();
</pre>
<p><br/><strong>Step 3 &#8211; load data in Ajax</strong><br />
We now need to get the data that will be refreshed from the server.<br />
There are endless implementations for that.<br />
Here is what I used.</p>
<pre class="brush: jscript; title: ; notranslate">
function ajax(page){
	var xmlhttp;
	if (window.XMLHttpRequest)	  {// code for IE7+, Firefox, Chrome, Opera, Safari
	  xmlhttp=new XMLHttpRequest();
	}
	else{// code for IE6, IE5
	  xmlhttp=new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;);
	}

	xmlhttp.onreadystatechange=function(){
		if (xmlhttp.readyState==4 &amp;&amp; xmlhttp.status==200){
			updateText(xmlhttp.responseText); //the method to be called when the data is fetched
		}
	}
	xmlhttp.open(&quot;GET&quot;,&quot;test.php?page=&quot;+page,true);
	xmlhttp.send();
}
</pre>
<p>Of course you will have to put the data on the server. I have used in my example a simple php page which receives the page as a parameter, but you can also use static html files.</p>
<p><br/><strong>Step 4 &#8211; update page data in an inner div</strong><br />
After you got the the data from the server you need to print it on the screen.<br />
You can so it simply like this:</p>
<pre class="brush: jscript; title: ; notranslate">
document.getElementById('myDiv').innerHTML = theData;
</pre>
<p>In my example I used an animation which makes things a bit cooler, I will talk about that later on.</p>
<p><br/><strong>Step 5 &#8211; push the page to the history</strong><br />
In regular page switch, the new page address is updated in the browser address bar and it also enters the history stack of the browser.<br />
We will imitate this behavior like this:</p>
<pre class="brush: jscript; title: ; notranslate">
history.pushState('', pageTitle, pageAddress);
</pre>
<p><br/><strong>Step 6 &#8211; handle history back/forward actions</strong><br />
Now that we have pushed our new fake page to the history stack we also need to be prepared when this fake page is popped from the history.</p>
<pre class="brush: jscript; title: ; notranslate">
window.onpopstate = function(event) {
	var currentPage = location.pathname;
	updateContent();
}
</pre>
<p><br/><strong>Step 7 &#8211; handle pages mapping in your server for direct links</strong><br />
You probably also should be prepared for the possibility that users will want to access the inner pages directly.<br />
You can achieve this by simple mapping in your web server. </p>
<p><br/><strong>Optional &#8211; add animation</strong><br />
You may chose to add some kind of animation, for example a clock while the data is loaded or some kind of text effect like I have done.<br />
This will make things even cooler.<br />
I have used a typing animation. This is how I have implemented it:</p>
<pre class="brush: jscript; title: ; notranslate">
function startAnimation(text){
	clearInterval(start);
	thediv.innerHTML=&quot;&quot;;
	thetext=text;

	if (document.getElementById||document.all){
		start=setInterval(&quot;animation()&quot;,20);
	}
	
}
	

function animation(){
	var oldLen = thediv.innerHTML.length;
	var finalLen = thetext.length;
	
	if(oldLen&lt;finalLen){
		thediv.innerHTML=thetext.substring(0,oldLen+1);
	}
}
</pre>
<p><br/><strong>Existing implementations</strong><br />
You should know that if you wish you can just use one of the existing implemtations on the net.<br />
<a href="https://gist.github.com/730603">Here is the very cool implementation by github</a>.</p>
<img src="http://feeds.feedburner.com/~r/aviyehuda/feed/~4/Sy-Ra2JzLOQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.aviyehuda.com/blog/2012/04/29/how-to-change-pages-in-a-web-application-in-the-age-of-html5/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.aviyehuda.com/blog/2012/04/29/how-to-change-pages-in-a-web-application-in-the-age-of-html5/</feedburner:origLink></item>
		<item>
		<title>4 JavaScript trivia questions that may help you understand the language a bit better</title>
		<link>http://feedproxy.google.com/~r/aviyehuda/feed/~3/bcJ7q6-F1fA/</link>
		<comments>http://www.aviyehuda.com/blog/2012/03/21/4-javascript-trivia-questions-that-may-help-you-understand-the-language-a-bit-better/#comments</comments>
		<pubDate>Wed, 21 Mar 2012 13:35:45 +0000</pubDate>
		<dc:creator>Avi</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Web_developing]]></category>

		<guid isPermaLink="false">http://www.aviyehuda.com/?p=2214</guid>
		<description><![CDATA[The next 4 Javascript questions may seem easy to some of you, but I am sure that more than a few will get confused. I believe that these 4 simple questions will help you understand a key feature of the <a class="more-link" href="http://www.aviyehuda.com/blog/2012/03/21/4-javascript-trivia-questions-that-may-help-you-understand-the-language-a-bit-better/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>The next 4 Javascript questions may seem easy to some of you, but I am sure that more than a few will get confused.<br />
I believe that these 4 simple questions will help you understand a key feature of the language.</p>
<p><br/><strong>Question: What will happen after executing the next JS code?</strong></p>
<pre class="brush: jscript; title: ; notranslate">
function outer(){
	var x=1;
	var inner = function(){
		alert(&quot;&gt;&quot;+x);
	}

	x=2;
	return inner;
}

outer();

</pre>
<p>1. Nothing<br />
2. alert &#8216;>undefined&#8217;<br />
3. alert &#8216;>1&#8242;<br />
4. alert &#8216;>2&#8242;</p>
<p><br/><strong>Answer:</strong><br />
Nothing, because outer() returned a function but it wasn&#8217;t executed.</p>
<p><br/><br/><strong>Question: What will happen after executing the next JS code?</strong></p>
<pre class="brush: jscript; title: ; notranslate">
function outer(){
	var x=1;
	var inner = function(){
		alert(&quot;&gt;&quot;+x);
	}
	x=2;
	return inner;
}

outer()();

</pre>
<p>1. Nothing<br />
2. alert &#8216;>undefined&#8217;<br />
3. alert &#8216;>1&#8242;<br />
4. alert &#8216;>2&#8242;</p>
<p><br/><strong>Answer:</strong><br />
alert &#8216;>2&#8242;, because the x that inner() uses is the same x the outer() uses.</p>
<p><br/><br/><strong>Question: What will happen after executing the next JS code?</strong></p>
<pre class="brush: jscript; title: ; notranslate">
function outer(){
	var x=1;
	var inner = function(x){
		alert(&quot;&gt;&quot;+x);
	}
	x=2;
	return inner;
}

outer()();

</pre>
<p>1. Nothing<br />
2. alert &#8216;>undefined&#8217;<br />
3. alert &#8216;>1&#8242;<br />
4. alert &#8216;>2&#8242;</p>
<p><br/><strong>Answer:</strong><br />
alert &#8216;>undefined&#8217;. Inner uses a variable x which is different than the outer x. The inner x is never initialized</p>
<p><br/><br/><strong>Question: What will happen after executing the next JS code?</strong></p>
<pre class="brush: jscript; title: ; notranslate">
function outer(){
	var x=1;
	var inner = function(x){
		alert(&quot;&gt;&quot;+x);
	}
	x=2;
	return inner;
}

outer()(3);

</pre>
<p>By now the answer should be obvious:  alert &#8216;>3&#8242; .</p>
<img src="http://feeds.feedburner.com/~r/aviyehuda/feed/~4/bcJ7q6-F1fA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.aviyehuda.com/blog/2012/03/21/4-javascript-trivia-questions-that-may-help-you-understand-the-language-a-bit-better/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.aviyehuda.com/blog/2012/03/21/4-javascript-trivia-questions-that-may-help-you-understand-the-language-a-bit-better/</feedburner:origLink></item>
		<item>
		<title>Use Clover to generate code coverage reports of your integration/automation tests</title>
		<link>http://feedproxy.google.com/~r/aviyehuda/feed/~3/HHT8TpF30Ck/</link>
		<comments>http://www.aviyehuda.com/blog/2011/12/21/use-clover-to-generate-code-coverage-reports-of-your-integrationautomation-tests/#comments</comments>
		<pubDate>Wed, 21 Dec 2011 04:45:29 +0000</pubDate>
		<dc:creator>Avi</dc:creator>
				<category><![CDATA[Clover]]></category>
		<category><![CDATA[code_coverage]]></category>

		<guid isPermaLink="false">http://www.aviyehuda.com/?p=885</guid>
		<description><![CDATA[Clover is a great tool for generating code coverage reports from your unit tests. It can be executed as a plugin in Eclipse, Maven or Ant. However, not everyone knows that it can also be used to collect coverage data <a class="more-link" href="http://www.aviyehuda.com/blog/2011/12/21/use-clover-to-generate-code-coverage-reports-of-your-integrationautomation-tests/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><!-- img style="float:left;padding:10px;" src="/images/clover/clover_anim.gif" / --><br />
<img style="float:left;padding:10px;" src="http://www.atlassian.com/en/wac/software/clover/overview/productLogo/imageBinary/clover_logo_landing.png"  /><br />
<a href="http://www.atlassian.com/software/clover/">Clover</a> is a great tool for generating code coverage reports from your unit tests. It can be executed as a plugin in Eclipse, Maven or Ant.<br />
However, not everyone knows that it can also be used to collect coverage data of integration tests.<br />
This post explains how to collect coverage data with clover at runtime.<br />
This post assumes that you already know what are unit and integration tests.<br />
This post assumes that you know what Clover is, and already used it either with Eclipse, Ant or Maven.</p>
<p><font color='red'>*</font>Let me assured you that even though the directions bellow seems complicated and clumsy at first, after doing them once or twice it is really easy to repeat them.</p>
<p><br/><br />
<strong>Motivation</strong><br />
The default action of Clover is to gather code coverage information during build time or compile time. Therefore, This information includes just the coverage data created by unit tests.</p>
<p>If you are developing web applications, you probably use more technologies to test your applications beside unit tests. These technologies may include HTTPUnit/<a href="http://www.aviyehuda.com/category/java/java-technologies/htmlunit-java-technologies-java/">HTMLUnit </a>or automation technologies (like Selenium). These technologies do not work at build time, they can only work during run time, where a web server is up and running and HTTP calls are made.<br />
As a result, the code coverage made during build time is not reflecting the actual code coverage. We should be able to test the coverage while a server is running.</p>
<p><br/><br />
<strong>The idea</strong><br />
The idea is that we will first run clover regularly during build time. We will than take the clover artifacts, put them in our server and then run the integration tests.<br />
While running the integration tests, the clover database will be updated and we would be able to generate reports from it which will reflect both unit and integration tests.</p>
<p><br/><br />
<strong>Step 1 &#8211; Preparation</strong></p>
<ul>
<li>Make sure that you have a web/application server (Tomcat/JBoss/weblogic&#8230;) with your web application already deployed.</li>
<li>Execute clover on your application as you would normally do (either by compiling the code on eclipse or by building with Maven or Ant, it doesn&#8217;t matter).<br />
<br/>The result of this action would be:</p>
<ol>
<li><strong>Clover DB files.</strong><br />
One of the outcome of executing the clover on your code are the DB files.<br />
The DB files hold all the information about your code and the coverage itself.</p>
<p>The location of those files may change depending on the way you use clover and according to the way you configured clover in your environment.</p>
<p>This is how the files looks like<br />
<center><img src="/images/clover/db.png" /></center></p>
<p>the .db file holds the information regarding your code (classes, methods and so on). All the other files hold all the coverage data.</p>
<p>It is important that you will locate those files because we are going to use them in the next step.</li>
<li><strong>An instrumented code.</strong><br />
Another outcome of clover is that it instruments your code. A clover call is injected into each method so it would be reported in the coverage calculation.<br />
We will need this code. we will use this instrumented code in runtime to update the coverage data.</p>
<p>If you use Eclipse than the generated classes would be instrumented. If you use Maven or Ant than most chances are that a jar with all the instrumented code would be generated separately.<br />
Search the instrument code jar. Again, I can&#8217;t tell you exactly where it is located, but usually it generates a jar with a &#8216;clover&#8217; postfix. Example: if your jar name is my_app.jar, than the generated instrumented code jar will probably be something like my_app-clover.jar.<br />
So you will need to do some detective work here to find the instrumented classes/jar. If you are not sure whether the classes are instrumented or not, just decompile one of them with  Jad and search for the word clover inside of it.	</li>
<li><strong>A code coverage report.</strong><br />
This is a report with the unit test coverage. We don&#8217;t really need this, but it would be good so that we would be able to compare it with the report we will generate at the end.</li>
</ol>
</li>
</ul>
<p><br/><br />
<strong>Step 2 &#8211; Updating the server</strong><br />
The next steps are very important, please make sure you do them properly.</p>
<ul>
<li>Replacing the existing application jar/classes with the instrumented jar/classes.<br />
Take the instrumented jar/classes  that were created by the clover and add it to your server&#8217;s classpath instead of the original jar/classes.<br />
The instrumented code will cause the clover DB to be updated with the runtime data.</li>
<p><br/></p>
<li>Adding clover jars and license.<br />
Since we will use clover on runtime we will need also the clover jars in our server&#8217;s classpath.<br />
So add the clover own jars to your server&#8217;s classpath. If you are using clover with Eclipse than these jars are located in the plugin folder of Eclipse. If you are using Maven than they will be loacted in your repository.</p>
<p><font color='red'>*</font> Make sure you are using the same version of clover in your server as you used to generate the DB files and instrumented code, otherwise it will not work and you will get error messages.<br />
Also add the clover license file to the same location as the jars.</li>
<p><br/>
<li>Adding the clover <a href="http://www.aviyehuda.com/java/">java </a>argument.<br />
Add the following java arg <strong>-Dclover.initstring.basedir={<em>location of the db files that were created by the clover</em>}</strong>.<br />
<font color='red'>*</font>Notice &#8211; the path you have entered above is the path of the <strong>folder </strong>which contains the DB files.<br />
Example:<br />
-Dclover.initstring.basedir=C:/workspace/MyWebApp/target/clover.<br />
This java argument is used by the clover to locate the DB files and update them.</li>
</ul>
<p><br/><br />
<strong>Step 3 &#8211; Restarting the server and running the tests</strong><br />
Now that hopefully all is set properly all that you need to do now is to restart your server and than running your integration tests.<br />
The tests should trigger the instrumented code which will call the clover API&#8217;s and will update the clover DB. </p>
<ol>
While running the tests:</p>
<li>Look at your log/console and search for error messages from clover.</li>
<li>Look at the folder which holds the clover DB files. If everything is going as it should, new files will be created in this folder while running the tests. </li>
</ol>
<p>If not everything is going well the first time, don&#8217;t discourage, just go over each of the steps again.</p>
<p><br/><br />
<strong>Step 4  &#8211; Generating an updated report</strong><br />
If everything went well and new files were created in the DB folder than that means you just need to generate a new report.<br />
If you are using clover with eclipse than you can simply push the reload button <img src="/images/clover/refresh.png"  />  to reload the coverage data.<br />
If you are using Maven or Ant you can execute just the task which generates the report.<br />
Another way is to use the clover <a href="http://confluence.atlassian.com/display/CLOVER/HtmlReporter">HtmlReporter </a>to generate a report easily.</p>
<p>Now compare the new report to the old report. You should see that the new report coverage is much bigger than the old one since it contains also the integration tests coverage.</p>
<p><font color='red'>*</font>Notice that not all the data is updated, even though the percentages are being updated, for some reason the calls counter does not.</p>
<p><br/><br />
To summarize. As mentioned; yes, these instructions seems a bit complicated but after you succeed the first time, it is very easy to repeat it. In the company I work for we even made this whole process automatic and we are able to generate a full coverage report with unit and integrated tests combined.</p>
<p><br/><br />
<center><img src="/images/clover/report.png" width="50%" /></center></p>
<img src="http://feeds.feedburner.com/~r/aviyehuda/feed/~4/HHT8TpF30Ck" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.aviyehuda.com/blog/2011/12/21/use-clover-to-generate-code-coverage-reports-of-your-integrationautomation-tests/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://www.aviyehuda.com/blog/2011/12/21/use-clover-to-generate-code-coverage-reports-of-your-integrationautomation-tests/</feedburner:origLink></item>
		<item>
		<title>Android development – Custom Animation</title>
		<link>http://feedproxy.google.com/~r/aviyehuda/feed/~3/D7FLj4sAg4M/</link>
		<comments>http://www.aviyehuda.com/blog/2011/07/01/android-development-custom-animation/#comments</comments>
		<pubDate>Fri, 01 Jul 2011 16:19:15 +0000</pubDate>
		<dc:creator>Avi</dc:creator>
				<category><![CDATA[Android]]></category>

		<guid isPermaLink="false">http://www.aviyehuda.com/?p=1841</guid>
		<description><![CDATA[Android developers web site provide you with 2 predefined animation techniques which you can use in your applications &#8211; Tween animation and frame animation. They are super easy to implement and work quite nice. If you are using Android 3.0 <a class="more-link" href="http://www.aviyehuda.com/blog/2011/07/01/android-development-custom-animation/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><img  style="float:left;padding:10px;" src="/images/android_anim.jpg" alt="android"  /><br />
<em>Android developers web site provide you with 2 predefined animation techniques which you can use in your applications &#8211; <a href="http://developer.android.com/guide/topics/graphics/view-animation.html#tween-animation">Tween animation </a> and <a href="http://developer.android.com/guide/topics/graphics/view-animation.html#frame-animation">frame animation</a>. They are super easy to implement and work quite nice.<br />
If you are using Android 3.0 or above, you should check out <a href="http://developer.android.com/guide/topics/graphics/prop-animation.html">Property Animation </a>technicqe. But what if you need to create your own customized animations and you are using older versions? Don&#8217;t worry, that is easy to do as well, here is how you do it.</em></p>
<p><br/></p>
<p>To create a customized animation you need to follow these 3 steps.<br />
For the explanation, we will create a simple animation that changes the background of a button gradually from black to red.</p>
<p><strong>Step 1 &#8211; Extend the Animation class and set the properties</strong><br />
Create a class which extends Android <a href="http://developer.android.com/reference/android/view/animation/Animation.html">Animation </a>class.<br />
This class will hold the logic of your animation.<br />
See my example:</p>
<pre class="brush: java; title: ; notranslate">
public class BGColorAnimation extends Animation {
	
	private View view;
	private int currentRedColor;
	
	//The steps to skip between colors
	private static int STEP_SIZE=30;  
	private static int ANIMATION_DURATION=50;

	public BGColorAnimation(View view) {
		this.view=view;
		setDuration(ANIMATION_DURATION);
		setRepeatCount(255/STEP_SIZE);
		setFillAfter(true);
		setInterpolator(new AccelerateInterpolator());
		
		setAnimationListener(new MyAnimationListener());
	}
}
</pre>
<ul>
<li>As you see, there is not much in this class since my animation is not that complicated.</li>
<li>Notice that I have made all the necessary animation parameters initialization from inside the constructor, but you can defiantly initialize them from outside the class.</li>
<li>There are 2 important parameters which determines the behavior of the animation:
<ol>
<li>RepeatCount &#8211; the number of steps this animation has.</li>
<li>Duration &#8211; the sleep time between 2 steps.</li>
</ol>
</li>
<li>On each step, the animation listener will be triggered.</li>
</ul>
<p><strong>Step 2 &#8211; Implement AnimationListener interface</strong><br />
Create a class which implements <a href="http://developer.android.com/reference/android/view/animation/Animation.AnimationListener.html">Animation.AnimationListener</a>.<br />
As mentioned, it is triggered on each animation step.</p>
<pre class="brush: java; title: ; notranslate">
class MyNumbersAnimationListener implements AnimationListener{
	    	private int index;

	    	@Override
		public void onAnimationEnd(Animation animation) {
			
		}

		@Override
		public void onAnimationRepeat(Animation animation) {
			// Change color of the view
			view.setBackgroundColor(
				Color.rgb(currentRedColor+=STEP_SIZE, 0, 0));
		}

		@Override
		public void onAnimationStart(Animation animation) {
			view.setBackgroundColor(Color.BLACK);
			currentRedColor=0;
		}
		
	}
	  
</pre>
<p><br/><br />
In fact, I see no reason why not doing both steps in the same class:<br />
<br/></p>
<pre class="brush: java; title: ; notranslate">
public class BGColorAnimation extends Animation implements
		Animation.AnimationListener {

	private View view;
	private int currentRedColor;

	// The steps to skip between colors
	private static int STEP_SIZE= 30;
	private static int ANIMATION_DURATION = 50;

	public BGColorAnimation(View view) {
		this.view = view;
		setDuration(ANIMATION_DURATION);
		setRepeatCount(255 / STEP_SIZE);
		setFillAfter(true);
		setInterpolator(new AccelerateInterpolator());

		setAnimationListener(this);
	}

	@Override
	public void onAnimationEnd(Animation animation) {

	}

	@Override
	public void onAnimationRepeat(Animation animation) {
		view.setBackgroundColor(
			Color.rgb(currentRedColor += STEP_SIZE, 0, 0));
	}

	@Override
	public void onAnimationStart(Animation animation) {
		view.setBackgroundColor(Color.BLACK);
		currentRedColor = 0;
	}

}
</pre>
<p><strong>Step 3 &#8211; Start the animation from a view</strong><br />
Animations are triggered from a view.<br />
Example:</p>
<pre class="brush: java; title: ; notranslate">
Button button = (Button)findViewById(R.id.b_colors);
button.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					button.startAnimation(new BGColorAnimation(button));
				}
			});
</pre>
<p><a href="/downloads/AnimationTest.zip"><img src="/ficons/zip.gif" alt="zip"> Download demo project</a></p>
<img src="http://feeds.feedburner.com/~r/aviyehuda/feed/~4/D7FLj4sAg4M" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.aviyehuda.com/blog/2011/07/01/android-development-custom-animation/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		<feedburner:origLink>http://www.aviyehuda.com/blog/2011/07/01/android-development-custom-animation/</feedburner:origLink></item>
		<item>
		<title>Android quick tip: use System.arraycopy()</title>
		<link>http://feedproxy.google.com/~r/aviyehuda/feed/~3/o0JPskVxM30/</link>
		<comments>http://www.aviyehuda.com/blog/2011/06/25/android-quick-tip-use-system-arraycopy/#comments</comments>
		<pubDate>Fri, 24 Jun 2011 22:15:22 +0000</pubDate>
		<dc:creator>Avi</dc:creator>
				<category><![CDATA[Android]]></category>

		<guid isPermaLink="false">http://www.aviyehuda.com/?p=1844</guid>
		<description><![CDATA[Well it&#8217;s a well known fact that the java native function System.arraycopy() is a useful way to copy one array to another since it is native, but is that also the case for Android? And if so, how much more <a class="more-link" href="http://www.aviyehuda.com/blog/2011/06/25/android-quick-tip-use-system-arraycopy/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Well it&#8217;s a well known fact that the java native function <a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/System.html#arraycopy(java.lang.Object, int, java.lang.Object, int, int)"> System.arraycopy()</a> is a useful way to copy one array to another since it is native, but is that also the case for Android? And if so, how much more useful is it?</p>
<p>To answer these questions I have made a simple test and ran it as a java program on my PC and than as an Android activity. </p>
<p>Here is the test for the PC:</p>
<pre class="brush: java; title: ; notranslate">
 private static final int SIZE_OF_ARRAY = 10000000;
	private static long time;

	
	public static void main(String[] args) {

		        Integer [] sourceArray = new Integer[SIZE_OF_ARRAY];
		        Integer [] destinationArray = new Integer[SIZE_OF_ARRAY];
		        fillArray(sourceArray);
		        
		        startBenchmark();
		        naiveCopy(sourceArray,destinationArray);
		        stopBenchmark();
		        
		        startBenchmark();
		        System.arraycopy(sourceArray, 0, destinationArray, 0,
						  sourceArray.length);
		        stopBenchmark();
		    }



			private static void naiveCopy(Integer [] src, Integer [] dst) {
				for (int i = 0; i &lt; src.length; i++) {
					dst[i]=src[i];
				}
				
			}

			private static void fillArray(Integer [] src) {
				for (int i = 0; i &lt; src.length; i++) {
					src[i]=i;
				}
				
			}
			
			private static void startBenchmark() {
				time = System.currentTimeMillis();
			}
			
			private static void stopBenchmark() {
				time = System.currentTimeMillis() - time;
				System.out.println( &quot;time=&quot;+time);
				
			}
</pre>
<p>Here are the results while running it from my PC (java 7, 8GB memory, CPU intel i5):<br />
Naive algorithm &#8211; 14 ms<br />
System.arraycopy(); &#8211; 6 ms.</p>
<p>Arraycopy does the task in less than half of the time.</p>
<p>Now to use it on Android &#8211; here is the code:</p>
<pre class="brush: java; title: ; notranslate">
public class ArrayCopyTestActivity extends Activity {
    private static final int SIZE_OF_ARRAY = 1000000;
	private long time;

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Integer [] sourceArray = new Integer[SIZE_OF_ARRAY];
        Integer [] dst = new Integer[SIZE_OF_ARRAY];
        fillArray(sourceArray);
        
        startBenchmark();
        naiveCopy(sourceArray,dst);
        stopBenchmark();
        
        
       
        startBenchmark();
        System.arraycopy(sourceArray, 0, dst, 0, sourceArray.length);
        stopBenchmark();
    }



	private void naiveCopy(Integer [] src, Integer [] dst) {
		for (int i = 0; i &lt; src.length; i++) {
			dst[i]=src[i];
		}
		
	}

	private void fillArray(Integer [] src) {
		for (int i = 0; i &lt; src.length; i++) {
			src[i]=i;
		}
		
	}
	
	private void startBenchmark() {
		time = System.currentTimeMillis();
	}
	
	private void stopBenchmark() {
		time = System.currentTimeMillis() - time;
		Log.d(&quot;array copy test&quot;, &quot;time=&quot;+time);
		
	}
}
</pre>
<p>* Notice I have reduced the size of the Array from 10 million to 1 million, this is due to restrictions on memory for applications in Android.</p>
<p><br/><br />
The results from running it on my device (nexus 1):<br />
Naive algorithm &#8211; <font color=red>182 ms</font><br />
System.arraycopy(); &#8211; 12 ms.</p>
<p>This means that the fact that System.arraycopy() is better than the regular copy is even more true for Android.<br />
In short than, always use  <strong>System.arraycopy()</strong> especially on Android.</p>
<p><a href="/downloads/arraycopy/ArrayCopyTest.java"><img src="/ficons/text.gif" alt="" /> Test for PC</a><br />
<a href="/downloads/arraycopy/ArrayCopyTestActivity.java"><img src="/ficons/text.gif" alt="" /> Test for Android</a></p>
<img src="http://feeds.feedburner.com/~r/aviyehuda/feed/~4/o0JPskVxM30" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.aviyehuda.com/blog/2011/06/25/android-quick-tip-use-system-arraycopy/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://www.aviyehuda.com/blog/2011/06/25/android-quick-tip-use-system-arraycopy/</feedburner:origLink></item>
		<item>
		<title>HtmlUnit – A quick introduction</title>
		<link>http://feedproxy.google.com/~r/aviyehuda/feed/~3/vomoUtXHnso/</link>
		<comments>http://www.aviyehuda.com/blog/2011/05/16/htmlunit-a-quick-introduction/#comments</comments>
		<pubDate>Mon, 16 May 2011 11:20:31 +0000</pubDate>
		<dc:creator>Avi</dc:creator>
				<category><![CDATA[HtmlUnit]]></category>
		<category><![CDATA[integration_tests]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.aviyehuda.com/?p=888</guid>
		<description><![CDATA[HtmlUnit is an open source java library for creating HTTP calls which imitate the browser functionality. HtmlUnit is mostly used for integration testing upon Unit test frameworks such as JUnit or TestNG. This is done by requesting web pages and <a class="more-link" href="http://www.aviyehuda.com/blog/2011/05/16/htmlunit-a-quick-introduction/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<ul>
<li> HtmlUnit is an open source java library for creating HTTP calls which imitate the browser functionality.
</li>
<li> HtmlUnit is mostly used for integration testing upon Unit test frameworks such as JUnit or TestNG. This is done by requesting web pages and asserting the results.
</li>
</ul>
<p><a name="Simple_Example"></a><br />
<h2> Simple Example </h2>
<hr />
<pre class="brush: java; title: ; notranslate">@Test
public void testGoogle(){
	WebClient webClient = new WebClient();
	HtmlPage currentPage = webClient.getPage(&quot;http://www.google.com/&quot;);
	assertEquals(&quot;Google&quot;, currentPage.getTitleText());
}</pre>
<p><a name="WebClient"></a><br />
<h2> WebClient </h2>
<hr />
<ul>
<li> As you can see in the example, the WebClient is the starting point. It is the browser simulator.
</li>
<li> WebClient.getPage() is just like typing an address in the browser. It returns an HtmlPage object.
</li>
</ul>
<p><a name="HtmlPage"></a><br />
<h2> HtmlPage </h2>
<hr />
<ul>
<li> HtmlPage represents a single web page along with all of it&#8217;s client&#8217;s data (HTML, JavaScript, CSS &#8230;).
</li>
<li> The HtmlPage lets you access to many of a web page content:
</li>
</ul>
<p><a name="Page_source"></a><br />
<h3> Page source </h3>
<ul>
<li> You can receive the page source as text or as XML.
</li>
</ul>
<pre class="brush: java; title: ; notranslate">HtmlPage currentPage = 
		webClient.getPage(&quot;http://www.google.com/&quot;);
String textSource = currentPage.asText();
String xmlSource = currentPage.asXml();</pre>
<p><a name="HTML_Elements"></a><br />
<h3> HTML Elements </h3>
<ul>
<li> HtmlPage lets you ability to access any of the page HTML elements and all of their attributes and sub elements. This includes tables, images, input fields, divs or any other Html element you may imagine.
</li>
<li> Use the function <b>getHtmlElementById()</b> to get any of the page elements.
</li>
</ul>
<pre class="brush: java; title: ; notranslate">WebClient webClient = new WebClient();
HtmlPage currentPage = webClient.getPage(&quot;http://www.google.com/&quot;);
HtmlImage imgElement = (HtmlImage)currentPage.getHtmlElementById(&quot;logo&quot;);
System.out.println(imgElement.getAttribute(&quot;src&quot;));</pre>
<p><a name="Anchors"></a><br />
<h3> Anchors </h3>
<ul>
<li> Anchor is the representation of the Html tag <i>&lt;a href=&#8221;&#8230;&#8221; &gt;link&lt;/a&gt;</i>.
</li>
<li> Use the functions <b>getAnchorByName()</b>, <b>getAnchorByHref()</b> and <b>getAnchorByText()</b> to easily access any of the anchors in the page.
</li>
</ul>
<pre class="brush: java; title: ; notranslate">WebClient webClient = new WebClient();
HtmlPage currentPage = webClient.getPage(&quot;http://www.google.com/&quot;);
HtmlAnchor advancedSearchAn = 
		currentPage.getAnchorByText(&quot;Advanced Search&quot;);
currentPage = advancedSearchAn.click();
assertEquals(&quot;Google Advanced Search&quot;,currentPage.getTitleText());</pre>
<p><a name="Dom_elements_by_XPath"></a><br />
<h3> Dom elements by XPath </h3>
<ul>
<li> You can access any of the page elements by using <a href="http://www.w3schools.com/xpath/xpath_syntax.asp" class="external text" title="http://www.w3schools.com/xpath/xpath_syntax.asp" rel="nofollow">XPath</a>.
</li>
</ul>
<pre class="brush: java; title: ; notranslate">WebClient webClient = new WebClient();
HtmlPage currentPage = 
	webClient.getPage(&quot;http://www.google.com/search?q=avi&quot;);
 
//Using XPath to get the first result in Google query
HtmlElement element = (HtmlElement)currentPage.getByXPath(&quot;//h3&quot;).get(0);
DomNode result = element.getChildNodes().get(0);</pre>
<p><a name="Form_control"></a><br />
<h3> Form control </h3>
<ul>
<li> A large part of controlling your HTML page is to control the form elements:</p>
<ul>
<li> HtmlForm
</li>
<li> HtmlTextInput
</li>
<li> HtmlSubmitInput
</li>
<li> HtmlCheckBoxInput
</li>
<li> HtmlHiddenInput
</li>
<li> HtmlPasswordInput
</li>
<li> HtmlRadioButtonInput
</li>
<li> HtmlFileInput
</li>
</ul>
</li>
</ul>
<pre class="brush: java; title: ; notranslate">WebClient webClient = new WebClient();
HtmlPage currentPage = webClient.getPage(&quot;http://www.google.com/&quot;);
 
//Get the query input text
HtmlInput queryInput = currentPage.getElementByName(&quot;q&quot;);
queryInput.setValueAttribute(&quot;aviyehuda&quot;);
 
//Submit the form by pressing the submit button
HtmlSubmitInput submitBtn = currentPage.getElementByName(&quot;btnG&quot;);
currentPage = submitBtn.click();</pre>
<p><a name="Tables"></a><br />
<h3> Tables </h3>
<pre class="brush: java; title: ; notranslate">currentPage = webClient.getPage(&quot;http://www.google.com/search?q=htmlunit&quot;);
final HtmlTable table = currentPage.getHtmlElementById(&quot;nav&quot;);
for (final HtmlTableRow row : table.getRows()) {
System.out.println(&quot;Found row&quot;);
    for (final HtmlTableCell cell : row.getCells()) {
       System.out.println(&quot;   Found cell: &quot; + cell.asText());
    }
}</pre>
<p><a name="JavaScript_support"></a><br />
<h2> JavaScript support </h2>
<hr />
<ul>
<li> HtmlUnit uses the <a href="http://www.mozilla.org/rhino/" class="external text" title="http://www.mozilla.org/rhino/" rel="nofollow">Mozilla Rhino</a> JavaScript engine.
</li>
<li> This lets you the ability to run pages with JavaScript or even run JavaScript code by command.
</li>
</ul>
<pre class="brush: java; title: ; notranslate">ScriptResult result = currentPage.executeJavaScript(JavaScriptCode);</pre>
<ul>
<li> By default JavaScript exceptions will crash your tests. If you wish to ignore JavaScript exceptions use this:
</li>
</ul>
<pre class="brush: java; title: ; notranslate">webClient().setThrowExceptionOnScriptError(false);</pre>
<ul>
<li> If you would like to turn off the JavaScript all together, use this:
</li>
</ul>
<pre class="brush: java; title: ; notranslate">currentPage.getWebClient().setJavaScriptEnabled(false);</pre>
<p><a name="HTTP_elements"></a><br />
<h2> HTTP elements </h2>
<hr />
<a name="URL"></a><br />
<h3> URL </h3>
<pre class="brush: java; title: ; notranslate">WebClient webClient = new WebClient();
HtmlPage currentPage = 
	webClient.getPage(&quot;http://www.google.co.uk/search?q=htmlunit&quot;);
URL url = currentPage.getWebResponse().getRequestSettings().getUrl()</pre>
<p><a name="Response_status"></a><br />
<h3> Response status </h3>
<pre class="brush: java; title: ; notranslate">WebClient webClient = new WebClient();
HtmlPage currentPage = webClient.getPage(&quot;http://www.google.com/&quot;);
assertEquals(200,currentPage.getWebResponse().getStatusCode());
assertEquals(&quot;OK&quot;,currentPage.getWebResponse().getStatusMessage());</pre>
<p><a name="Cookies"></a><br />
<h3> Cookies </h3>
<pre class="brush: java; title: ; notranslate">Set&lt;Cookie&gt; cookies = webClient.getCookieManager().getCookies();
for (Cookie cookie : cookies) {
	System.out.println(cookie.getName() + &quot; = &quot; + cookie.getValue());
}</pre>
<p><a name="Response_headers"></a><br />
<h3> Response headers </h3>
<pre class="brush: java; title: ; notranslate">WebClient webClient = new WebClient();
HtmlPage currentPage = 
	webClient.getPage(&quot;http://www.google.com/search?q=htmlunit&quot;);

List&lt;NameValuePair&gt; headers = 
	currentPage.getWebResponse().getResponseHeaders();
for (NameValuePair header : headers) {
	System.out.println(header.getName() + &quot; = &quot; + header.getValue());
}</pre>
<p><a name="Request_parameters"></a><br />
<h3> Request parameters </h3>
<pre class="brush: java; title: ; notranslate">List&lt;NameValuePair&gt; parameters = 
	currentPage.getWebResponse().getRequestSettings().getRequestParameters();
for (NameValuePair parameter : parameters) {
	System.out.println(parameter.getName() + &quot; = &quot; + parameter.getValue());
}</pre>
<p><a name="Making_assertions"></a><br />
<h2> Making assertions </h2>
<hr />
<ul>
<li> HtmlUnit comes with a set of assetions:
</li>
</ul>
<pre>   assertTitleEquals(HtmlPage, String)
   assertTitleContains(HtmlPage, String)
   assertTitleMatches(HtmlPage, String)
   assertElementPresent(HtmlPage, String)
   assertElementPresentByXPath(HtmlPage, String)
   assertElementNotPresent(HtmlPage, String)
   assertElementNotPresentByXPath(HtmlPage, String)
   assertTextPresent(HtmlPage, String)
   assertTextPresentInElement(HtmlPage, String, String)
   assertTextNotPresent(HtmlPage, String)
   assertTextNotPresentInElement(HtmlPage, String, String)
   assertLinkPresent(HtmlPage, String)
   assertLinkNotPresent(HtmlPage, String)
   assertLinkPresentWithText(HtmlPage, String)
   assertLinkNotPresentWithText(HtmlPage, String)
   assertFormPresent(HtmlPage, String)
   assertFormNotPresent(HtmlPage, String)
   assertInputPresent(HtmlPage, String)
   assertInputNotPresent(HtmlPage, String)
   assertInputContainsValue(HtmlPage, String, String)
   assertInputDoesNotContainValue(HtmlPage, String, String)
</pre>
<p><br/></p>
<ul>
<li> You can still of course use the framework&#8217;s assertions. For example, if you are using JUnit, you can still use assertTrue() and so on.
</li>
<li> Here are a few examples:
</li>
</ul>
<pre class="brush: java; title: ; notranslate">WebClient webClient = new WebClient();
HtmlPage currentPage = 
      webClient.getPage(&quot;http://www.google.com/search?q=htmlunit&quot;);
 
assertEquals(200,currentPage.getWebResponse().getStatusCode());
assertEquals(&quot;OK&quot;,currentPage.getWebResponse().getStatusMessage());
WebAssert.assertTextPresent(currentPage, &quot;htmlunit&quot;);
WebAssert.assertTitleContains(currentPage, &quot;htmlunit&quot;);
WebAssert.assertLinkPresentWithText(currentPage, &quot;Advanced search&quot;);
assertTrue(currentPage.getByXPath(&quot;//h3&quot;).size()&gt;0); //result number
assertNotNull(webClient.getCookieManager().getCookie(&quot;NID&quot;));</pre>
<p><a name="External_links"></a><br />
<h2> See also </h2>
<hr />
<ul>
<li> <a href="http://htmlunit.sourceforge.net/" class="external text" title="http://htmlunit.sourceforge.net/" rel="nofollow">Product main page</a>
</li>
<li> <a href="http://sourceforge.net/projects/htmlunit/" class="external text" title="http://sourceforge.net/projects/htmlunit/" rel="nofollow">Download page</a>
</li>
<li> <a href="http://htmlunit.sourceforge.net/dependencies.html" class="external text" title="http://htmlunit.sourceforge.net/dependencies.html" rel="nofollow">Jar dependencies</a>
</li>
</ul>
<p><br/></p>
<p><a href="/downloads/htmlUnitExample.zip"><img src="/ficons/zip.gif">&nbsp;Download example</a></p>
<img src="http://feeds.feedburner.com/~r/aviyehuda/feed/~4/vomoUtXHnso" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.aviyehuda.com/blog/2011/05/16/htmlunit-a-quick-introduction/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<feedburner:origLink>http://www.aviyehuda.com/blog/2011/05/16/htmlunit-a-quick-introduction/</feedburner:origLink></item>
	</channel>
</rss>
