<?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>ViralPatel.net</title>
	
	<link>http://viralpatel.net/blogs</link>
	<description>Tutorials, Java, J2EE, Struts, AJAX, JavaScript, CSS, Web 2.0, MySQL, Articles</description>
	<lastBuildDate>Thu, 23 May 2013 16:05:22 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/viralpatelnet" /><feedburner:info uri="viralpatelnet" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:emailServiceId>viralpatelnet</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><item>
		<title>Lazy Load Image &amp; WordPress Gravatar using JavaScript / JQuery</title>
		<link>http://feedproxy.google.com/~r/viralpatelnet/~3/7nvAOJStYG0/</link>
		<comments>http://viralpatel.net/blogs/lazy-load-image-wordpress-avatar-jquery/#comments</comments>
		<pubDate>Thu, 23 May 2013 12:52:02 +0000</pubDate>
		<dc:creator>Viral Patel</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[Gravatar]]></category>
		<category><![CDATA[search engine optimization]]></category>
		<category><![CDATA[Website optimization]]></category>
		<category><![CDATA[wordpress]]></category>

		<guid isPermaLink="false">http://viralpatel.net/blogs/?p=3052</guid>
		<description><![CDATA[A webpage load time plays a very crucial role in SEO and impacts your website ranking significantly. Google has already incorporated site speed as one of the several signals that it uses to determine search ranking. The faster your website loads the better it will perform in google ranking. There are several things one can [...]<div class='yarpp-related-rss'>
<h3>Related Posts</h3><ol>
<li><a href='http://viralpatel.net/blogs/set-maxlength-of-textarea-input-using-jquery-javascript/' rel='bookmark' title='How to:Set Maxlength of Textarea using jQuery/JavaScript'>How to:Set Maxlength of Textarea using jQuery/JavaScript</a></li>
<li><a href='http://viralpatel.net/blogs/jquery-ajax-tutorial-example-ajax-jquery-development/' rel='bookmark' title='jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery'>jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery</a></li>
<li><a href='http://viralpatel.net/blogs/tutorial-handle-browser-events-using-jquery-javascript-framework/' rel='bookmark' title='Tutorial: Handle browser events using jQuery JavaScript framework'>Tutorial: Handle browser events using jQuery JavaScript framework</a></li>
<li><a href='http://viralpatel.net/blogs/default-text-label-textbox-javascript-jquery/' rel='bookmark' title='Default Text Label in Textbox using JavaScript/jQuery'>Default Text Label in Textbox using JavaScript/jQuery</a></li>
<li><a href='http://viralpatel.net/blogs/ajax-post-method-example-using-javascript-jquery/' rel='bookmark' title='AJAX Post Method example using Javascript &amp; jQuery'>AJAX Post Method example using Javascript &#038; jQuery</a></li>
<li><a href='http://viralpatel.net/blogs/implement-drag-and-drop-example-jquery-javascript-html/' rel='bookmark' title='Drag and Drop Example using jQuery JavaScript in HTML'>Drag and Drop Example using jQuery JavaScript in HTML</a></li>
<li><a href='http://viralpatel.net/blogs/gravatar-manage-your-user-avatars-for-free/' rel='bookmark' title='Gravatar: Manage your user avatars for free'>Gravatar: Manage your user avatars for free</a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/2013/05/page-load-speed-viralpatel.png" alt="page-load-speed-viralpatel" width="516" height="165" class="aligncenter size-full wp-image-3063" /><br />
A webpage load time plays a very crucial role in SEO and impacts your website ranking significantly. Google has <a href="http://searchengineland.com/google-now-counts-site-speed-as-ranking-factor-39708">already incorporated site speed</a> as one of the several signals that it uses to determine search ranking. The faster your website loads the better it will perform in google ranking. </p>
<p>There are several things one can do to improve overall site speed. Like: </p>
<ol>
<li>Reduce number of http queries by combining JS and CSS files</li>
<li>GZip all the content before serving the request.</li>
<li>Compress images on web page with tools like http://tinypng.com</li>
<li>And many more&#8230;</li>
</ol>
<p>Reference: <a href="http://viralpatel.net/blogs/compress-php-css-js-javascript-optimize-website-performance/">Compress PHP, JS, CSS for Website Optimization</a></p>
<p>You may already have implemented most of these steps in your website. But there is always a room for optimization <img src='http://viralpatel.net/blogs/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Just take one of your site page URL and use <a href="https://developers.google.com/speed/pagespeed/insights">Google Pagespeed</a> tool to determine overall PageSpeed score. This tool and its plugin for firefox and chrome can be used to analyze several performance related aspects of a webpage.</p>
<p>Among several suggestions that PageSpeed offers, one particular is of our interest which is serving multiple HTTP requests. If your webpage has too many external JavaScripts / CSS files or too many image files, the browser will send a unique http request for each of those content during page load. This reduces the performance significantly there by impacting your seo. </p>
<p>Although you can combine and <a href="http://viralpatel.net/blogs/increase-performance-of-website-by-compressing-javascript/">compress</a> all JS and CSS files to reduce number of http requests, but that would not help much if your webpage has several images.</p>
<p>The first step in reducing number of Image requests is to combine all the small image icons in one big image sheet using a simple technique called <a href="http://css-tricks.com/css-sprites/">CSS Sprites</a>. I strongly suggest you to use CSS Sprite if you are not already doing this on your website.</p>
<h2>Lazy Image Loading</h2>
<p>After doing all these changes still if you have lots of images on your website, you might want to <strong>lazy load</strong> these images. Meaning load the image only when it is being viewed there by deferring http call until user is watching the image.</p>
<p>This technique can be very much useful in websites which display list of products with images. User can scroll through list and instead of loading all the product images while loading webpage, each image is loaded asynchronously when it comes in users viewport.</p>
<p>Now to achieve this we use simple JQuery snippet:</p>
<h3>Step 1: Change &lt;IMG&gt; tag</h3>
<p>First change the &lt;img&gt; tag for which you want to lazy load image to:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;!-- Before: --&gt;
&lt;img src=&quot;http://foo/product.png&quot; width=&quot;300px&quot; height=&quot;200px&quot; /&gt;

&lt;!-- After: --&gt;
&lt;img src=&quot;blank.gif&quot; class=&quot;lazy&quot; data-src=&quot;http://foo/product.png&quot; 
			width=&quot;300px&quot; height=&quot;200px&quot; /&gt;
</pre>
<p>Notice how we moved our image url from <code>src</code> to <code>data-src</code> attribute. Also we added <a rel="_new" href="http://img.viralpatel.net/blank.gif">blank.gif</a> which is 1 px transparent gif file in <code>src</code> attribute. We also added a CSS class <code>lazy</code> to the image. This is to mark the image for lazy loading in jquery code which we will see shortly. Also do not forget to mention <code>height</code> and <code>width</code> attribute with <code>&lt;img&gt;</code> tag. This make sure browser leave enough space around blank.gif to load original image. </p>
<p>Now on pageload, browser will load blank.gif file instead of product.png thus making http request more faster. If you have several images with <code>src=blank.gif</code>, browser will load it just once and use it from cache.</p>
<h3>Step 2: The JQuery Code Snippet</h3>
<p>We want to load original image once that image is in browsers visible area. Following JQuery snippet do this task.</p>
<pre class="brush: jscript; title: ; notranslate">
(function($) {
	var lazyloadImage = function(){

		$('img.lazy').each(function(){
			var distanceToTop = $(this).offset().top;
			var scroll = $(window).scrollTop();
			var windowHeight = $(window).height();
			var isVisible = distanceToTop - scroll &lt; windowHeight;
			if (isVisible) {
				$(this).attr('src', $(this).attr('data-src')).removeClass('lazy');
			}
		});

	};

	$(function(){
		$(window).scroll(function() {
			lazyloadImage();
		});
	});

	lazyloadImage();

})(jQuery);
</pre>
<p>In this snippet we hook a function to browsers scroll event. For each image that has <code>lazy</code> css class on it, we iterate and see if the image is in visible area. If it is then we just copy value from image&#8217;s <code>data-src</code> to its <code>src</code> attribute. Once the image&#8217;s src attribute changes, browser will automatically load its content. Note how we remove <code>lazy</code> class once the image is loaded to avoid further changes in DOM. </p>
<h3>Online Demo</h3>
<p>Check the online demo:  <a target="_new" href="http://viralpatel.net/blogs/demo/jquery/lazy-load-image.html"><b>Online Demo</b></a></p>
<h2>Further Optimization using data URI</h2>
<p>The above image lazy loading technique reduce the page size significantly during the load time, but it still performs an http request on blank.gif. If somehow browser is not caching blank.gif image, then it will unnecessarily perform multiple http requests for it for each lazy image.</p>
<p>We can further optimize this by using <a href="http://css-tricks.com/data-uris/" rel="nofollow" target="_new">Data URIs</a>. It is a technique by which image data is directly embedded into document using some URI instead of linking external images within <img> element or background-image in CSS.</p>
<p>The biggest reason why you want to do this is to save HTTP Requests. </p>
<p>Just change the <code>&lt;img&gt;</code> tag we saw previously to:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;!-- Before: --&gt;
&lt;img src=&quot;blank.gif&quot; class=&quot;lazy&quot; data-src=&quot;http://foo/product.png&quot; 
			width=&quot;300px&quot; height=&quot;200px&quot; /&gt;

&lt;!-- After: --&gt;
&lt;img src=&quot;data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==&quot; 
		class=&quot;lazy&quot; data-src=&quot;http://foo/product.png&quot; 
			width=&quot;300px&quot; height=&quot;200px&quot; /&gt;
</pre>
<p>So intead of linking to external image <code>blank.gif</code>, we embedded its content in src attribute of <code>&lt;img&gt;</code> element using data URI. This will significantly reduces number of http requests in your webpage.</p>
<h2>SEO Consideration</h2>
<p>Lazy loading images would improve site speed significantly. But it also makes images less crawlable. Search engines like Google indexes the images from a website and display those in Image search. So if your website&#8217;s main source of traffic is image search than you may not want to implement this optimization technique. </p>
<p>But as I said earlier, there is always room for optimization. You can keep main images on your webpage as it is and make other less significant images to load dynamically. For example the Avatar images that you display in each comment. These images are not significant for indexing. A blog article can be showing 50 comments each with an Avatar image. Instead of loading 50 images during pageload, you can make them lazy by using our lazy code snippet.</p>
<h2>Gravtar Images on WordPress</h2>
<p>WordPress uses something called <a rel="nofollow" target="_new" href="https://gravatar.com/">Gravtar</a> to show user avatar image in each comment. If a user does not have an avatar setup in gravtar.com then a default gravtar will be displayed.</p>
<p>Lazy loading these hundreds of gravtar images in a wordpress blog should definitely increase site speed by reducing all those http requests. Another advantage of doing this is to reduce HTTP redirect requests at pageload time. See below screen shot of Google PageSpeed.</p>
<p><img src="http://img.viralpatel.net/2013/05/google-pagespeed-redirect.png" alt="google-pagespeed-redirect" width="623" height="470" class="aligncenter size-full wp-image-3064" /></p>
<p>Notice how each http request generates an redirect request that browser must follow to load that image!! This is due to the fact that if a user has not setup gravtar image, then a default image will be displayed. You don&#8217;t want to load those 50 avatar images during load time and follow the redirects in case user doesnt have a gravtar.</p>
<p>So why not change our wordpress comment template and load these avatar images lazily.</p>
<p>If you check your wordpress theme&#8217;s comment template, you&#8217;ll notice a function <a rel="nofollow" target="_new" href="http://codex.wordpress.org/Function_Reference/get_avatar">get_avatar()</a> which is used to display user avatar image.</p>
<pre class="brush: php; title: ; notranslate">
//comment template
..
	&lt;?php get_avatar( $comment, 50 ); ?&gt;
..
</pre>
<p>WordPress&#8217;s <code>get_avatar</code> function will create an <code>&lt;img&gt;</code> tag with users avatar URL. We need to change the src attribute to data-src and use data-uri as mentioned above in src attribute.</p>
<p>But as wordpress does not provide users gravtar URL directly, we need to parse this information from get_avatar and use it to create our own <code>&lt;img&gt;</code> tag with lazy attribute.</p>
<p>Add below function in your wordpress theme&#8217;s functions.php file.</p>
<p>theme/&#8230;./functions.php</p>
<pre class="brush: php; title: ; notranslate">
function get_avatar_url($get_avatar){
    preg_match(&quot;/src='(.*?)'/i&quot;, $get_avatar, $matches);
    return $matches[1];
}
</pre>
<p>And then use get_avatar_url function in comment template like:</p>
<pre class="brush: php; title: ; notranslate">
//comment template
/* Before **
	&lt;?php get_avatar( $comment, 50 ); ?&gt;
*/

/* After */
..
&lt;img src=&quot;data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==&quot;
	width=&quot;50&quot; height=&quot;50&quot; class=&quot;lazy&quot;
	data-src=&quot;&lt;?php echo get_avatar_url(get_avatar( $comment, 50 )); ?&gt;&quot; /&gt;
</pre>
<p>This should render an avatar image with lazy attributes. Now combining this with our jquery code should load all the gravtar images in comment section asynchronously.</p>
<h2>I Don&#8217;t Want To Use JQuery</h2>
<p>If you are not keen on using JQuery snippet as you might not using JQuery alltogether in your website! No worries. Following JavaScript code from <a href="https://gist.github.com/miloplacencia/3931803" target="_new" rel="nofollow">Lorenzo Giuliani</a> does exactly same thing.</p>
<pre class="brush: jscript; title: ; notranslate">
/* lazyload.js (c) Lorenzo Giuliani
 * MIT License (http://www.opensource.org/licenses/mit-license.html)
 *
 * expects a list of:  
 * `&lt;img src=&quot;blank.gif&quot; data-src=&quot;my_image.png&quot; width=&quot;600&quot; height=&quot;400&quot; class=&quot;lazy&quot;&gt;`
 */
 
!function(window){
  var $q = function(q, res){
        if (document.querySelectorAll) {
          res = document.querySelectorAll(q);
        } else {
          var d=document
            , a=d.styleSheets[0] || d.createStyleSheet();
          a.addRule(q,'f:b');
          for(var l=d.all,b=0,c=[],f=l.length;b&lt;f;b++)
            l[b].currentStyle.f &amp;&amp; c.push(l[b]);
 
          a.removeRule(0);
          res = c;
        }
        return res;
      }
    , addEventListener = function(evt, fn){
        window.addEventListener
          ? this.addEventListener(evt, fn, false)
          : (window.attachEvent)
            ? this.attachEvent('on' + evt, fn)
            : this['on' + evt] = fn;
      }
    , _has = function(obj, key) {
        return Object.prototype.hasOwnProperty.call(obj, key);
      }
    ;
 
  function loadImage (el, fn) {
    var img = new Image()
      , src = el.getAttribute('data-src');
    img.onload = function() {
      if (!! el.parent)
        el.parent.replaceChild(img, el)
      else
        el.src = src;
 
      fn? fn() : null;
    }
    img.src = src;
  }
 
  function elementInViewport(el) {
    var rect = el.getBoundingClientRect()
 
    return (
       rect.top    &gt;= 0
    &amp;&amp; rect.left   &gt;= 0
    &amp;&amp; rect.top &lt;= (window.innerHeight || document.documentElement.clientHeight)
    )
  }
 
    var images = new Array()
      , query = $q('img.lazy')
      , processScroll = function(){
          for (var i = 0; i &lt; images.length; i++) {
            if (elementInViewport(images[i])) {
              loadImage(images[i], function () {
                images.splice(i, i);
              });
            }
          };
        }
      ;
    // Array.prototype.slice.call is not callable under our lovely IE8 
    for (var i = 0; i &lt; query.length; i++) {
      images.push(query[i]);
    };
 
    processScroll();
    addEventListener('scroll',processScroll);
 
}(this);
</pre>
<p>Just add above JavaScript code in your site and you are good to go.</p>
<p>Try this in your site today and see how much score you gain on Google PageSpeed <img src='http://viralpatel.net/blogs/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Check the online demo:  <a href="http://viralpatel.net/blogs/demo/jquery/lazy-load-image.html"><b>Online Demo</b></a></p>
<div class='yarpp-related-rss'>
<h3>Related Posts</h3><ol>
<li><a href='http://viralpatel.net/blogs/set-maxlength-of-textarea-input-using-jquery-javascript/' rel='bookmark' title='How to:Set Maxlength of Textarea using jQuery/JavaScript'>How to:Set Maxlength of Textarea using jQuery/JavaScript</a></li>
<li><a href='http://viralpatel.net/blogs/jquery-ajax-tutorial-example-ajax-jquery-development/' rel='bookmark' title='jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery'>jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery</a></li>
<li><a href='http://viralpatel.net/blogs/tutorial-handle-browser-events-using-jquery-javascript-framework/' rel='bookmark' title='Tutorial: Handle browser events using jQuery JavaScript framework'>Tutorial: Handle browser events using jQuery JavaScript framework</a></li>
<li><a href='http://viralpatel.net/blogs/default-text-label-textbox-javascript-jquery/' rel='bookmark' title='Default Text Label in Textbox using JavaScript/jQuery'>Default Text Label in Textbox using JavaScript/jQuery</a></li>
<li><a href='http://viralpatel.net/blogs/ajax-post-method-example-using-javascript-jquery/' rel='bookmark' title='AJAX Post Method example using Javascript &amp; jQuery'>AJAX Post Method example using Javascript &#038; jQuery</a></li>
<li><a href='http://viralpatel.net/blogs/implement-drag-and-drop-example-jquery-javascript-html/' rel='bookmark' title='Drag and Drop Example using jQuery JavaScript in HTML'>Drag and Drop Example using jQuery JavaScript in HTML</a></li>
<li><a href='http://viralpatel.net/blogs/gravatar-manage-your-user-avatars-for-free/' rel='bookmark' title='Gravatar: Manage your user avatars for free'>Gravatar: Manage your user avatars for free</a></li>
</ol>
</div>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=7nvAOJStYG0:7W1UcFmas4I:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=7nvAOJStYG0:7W1UcFmas4I:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=7nvAOJStYG0:7W1UcFmas4I:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?i=7nvAOJStYG0:7W1UcFmas4I:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=7nvAOJStYG0:7W1UcFmas4I:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=7nvAOJStYG0:7W1UcFmas4I:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=I9og5sOYxJI" border="0"></img></a>
</div>]]></content:encoded>
			<wfw:commentRss>http://viralpatel.net/blogs/lazy-load-image-wordpress-avatar-jquery/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://viralpatel.net/blogs/lazy-load-image-wordpress-avatar-jquery/</feedburner:origLink></item>
		<item>
		<title>21 JavaScript Tips and Tricks for JavaScript Developers</title>
		<link>http://feedproxy.google.com/~r/viralpatelnet/~3/7Txp1SIlKas/</link>
		<comments>http://viralpatel.net/blogs/javascript-tips-tricks/#comments</comments>
		<pubDate>Tue, 21 May 2013 12:58:29 +0000</pubDate>
		<dc:creator>Viral Patel</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[javascript events]]></category>
		<category><![CDATA[tips & tricks]]></category>

		<guid isPermaLink="false">http://viralpatel.net/blogs/?p=3056</guid>
		<description><![CDATA[If you are doing lot of JavaScript programming, you might find below list of code snippets very useful. Keep it handy (bookmark it) and save it for future reference. Here are 20 very useful JavaScript tips and tricks for you. Disclaimer: Not all these snippet are written by me. Some of them are collected from [...]<div class='yarpp-related-rss'>
<h3>Related Posts</h3><ol>
<li><a href='http://viralpatel.net/blogs/listbox-select-all-move-left-right-up-down-javascript/' rel='bookmark' title='Listbox options javascript select all,move left-right, move up-down'>Listbox options javascript select all,move left-right, move up-down</a></li>
<li><a href='http://viralpatel.net/blogs/javascript-array-remove-element-js-array-delete-element/' rel='bookmark' title='JavaScript Array Remove an Element'>JavaScript Array Remove an Element</a></li>
<li><a href='http://viralpatel.net/blogs/javascript-delete-multiple-values-options-listbox/' rel='bookmark' title='Deleting Multiple Values From Listbox in JavaScript'>Deleting Multiple Values From Listbox in JavaScript</a></li>
<li><a href='http://viralpatel.net/blogs/20-top-jquery-tips-tricks-for-jquery-programmers/' rel='bookmark' title='20 Top jQuery Tips &amp; Tricks for jQuery Programmers'>20 Top jQuery Tips &#038; Tricks for jQuery Programmers</a></li>
<li><a href='http://viralpatel.net/blogs/dynamic-add-textbox-input-button-radio-element-html-javascript/' rel='bookmark' title='Dynamically add button, textbox, input, radio elements in html form using JavaScript.'>Dynamically add button, textbox, input, radio elements in html form using JavaScript.</a></li>
<li><a href='http://viralpatel.net/blogs/dynamic-combobox-listbox-drop-down-using-javascript/' rel='bookmark' title='Dynamic combobox-listbox-drop-down using javascript'>Dynamic combobox-listbox-drop-down using javascript</a></li>
<li><a href='http://viralpatel.net/blogs/javascript-multiple-selection-listbox-problem-ms-internet-explorer/' rel='bookmark' title='Multiple Selection Listbox Javascript Problem in MS Internet Explorer'>Multiple Selection Listbox Javascript Problem in MS Internet Explorer</a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/2013/05/javscript-tips-viralpatelnet.png" alt="javscript-tips-viralpatelnet" width="473" height="135" class="aligncenter size-full wp-image-3057" /><br />
If you are doing lot of JavaScript programming, you might find below list of code snippets very useful. Keep it handy (bookmark it) and save it for future reference. </p>
<p>Here are 20 very useful JavaScript tips and tricks for you. </p>
<p><strong>Disclaimer:</strong> Not all these snippet are written by me. Some of them are collected from other sources on Internet.</p>
<h2>1. Converting JavaScript Array to CSV</h2>
<p>First one goes like this. You have a javascript array of strings (or numbers) and you want to convert it to comma separated values (csv). We&#8217;ll below is the code snippet:<br />
Reference: <a href="http://viralpatel.net/blogs/convert-javascript-arrays-to-csv/" rel="nofollow">Array to CSV in JavaScript</a></p>
<pre class="brush: jscript; title: ; notranslate">
var fruits = ['apple', 'peaches', 'oranges', 'mangoes'];
 
var str = fruits.valueOf();
 
//print str: apple,peaches,oranges,mangoes
</pre>
<p>The <code>valueOf()</code> method will convert an array in javascript to a comma separated string.</p>
<p>Now what if you want to use pipe (|) as delimeter instead of comma. You can convert a js array into a delimeted string using <code>join()</code> method. See below:</p>
<pre class="brush: jscript; title: ; notranslate">
var fruits = ['apple', 'peaches', 'oranges', 'mangoes'];
 
var str = fruits.join(&quot;|&quot;);
 
//print str: apple|peaches|oranges|mangoes
</pre>
<p>The <code>join()</code> method will convert the array into a pipe separated string.</p>
<p><iframe src="http://viralpatel.net/blogs/demo/js/javascript-tips/1.html" frameborder="0" width="100%" height="200px"></iframe></p>
<h2>2. Convert CSV to Array in JavaScript</h2>
<p>Now what if you want to convert a comma seprated string into a JavaScript array? We&#8217;ll there is a method for that too. You can use <code>split()</code> method to split a string using any token (for instance comma) and create an array.</p>
<p>Reference: <a href="http://viralpatel.net/blogs/convert-javascript-arrays-to-csv/" rel="nofollow">Array to CSV in JavaScript</a></p>
<p>In below example we split string <code>str</code> on comma (,) and create a <code>fruitsArray</code> array.</p>
<pre class="brush: jscript; title: ; notranslate">
var str = &quot;apple, peaches, oranges, mangoes&quot;;
 
var fruitsArray = str.split(&quot;,&quot;);
 
//print fruitsArray[0]: apple
</pre>
<p><iframe src="http://viralpatel.net/blogs/demo/js/javascript-tips/2.html" frameborder="0" width="100%" height="200px"></iframe></p>
<h2>3. Remove Array element by Index</h2>
<p>You have an array. You want to remove a perticular element from array based on its index. We&#8217;ll you can do so using <code>splice()</code> method. This method can add as well as removes element from an array. We will stick to its removal usage.<br />
Reference: <a rel="nofollow" href="http://viralpatel.net/blogs/javascript-array-remove-element-js-array-delete-element/">Remove element by array index</a></p>
<pre class="brush: jscript; title: ; notranslate">
function removeByIndex(arr, index) {
    arr.splice(index, 1);
}

test = new Array();
test[0] = 'Apple';
test[1] = 'Ball';
test[2] = 'Cat';
test[3] = 'Dog';

alert(&quot;Array before removing elements: &quot;+test);

removeByIndex(test, 2);

alert(&quot;Array after removing elements: &quot;+test);
</pre>
<p><iframe src="http://viralpatel.net/blogs/demo/js/javascript-tips/3.html" frameborder="0" width="100%" height="200px"></iframe></p>
<h2>4. Remove Array element by Value</h2>
<p>This one is very useful. You have an array and you want to remove an element based on its value (instead of index).<br />
Reference: <a rel="nofollow" href="http://viralpatel.net/blogs/javascript-array-remove-element-js-array-delete-element/">Remove element by array index</a></p>
<pre class="brush: jscript; title: ; notranslate">
function removeByValue(arr, val) {
    for(var i=0; i&lt;arr.length; i++) {
        if(arr[i] == val) {
            arr.splice(i, 1);
            break;
        }
    }
}

var somearray = [&quot;mon&quot;, &quot;tue&quot;, &quot;wed&quot;, &quot;thur&quot;]

removeByValue(somearray, &quot;tue&quot;);

//somearray will now have &quot;mon&quot;, &quot;wed&quot;, &quot;thur&quot;
</pre>
<p>See how in above code we defined a method <code>removeByValue</code> that takes serves the purpose. In JavaScript you can define new functions to classes at runtime (although this is discourage) using <code>prototypes</code>. </p>
<p>In below code snippet, we create a new method <code>removeByValue()</code> within <code>Array</code> class. So now you can call this method as any other arrays method.</p>
<pre class="brush: jscript; title: ; notranslate">
Array.prototype.removeByValue = function(val) {
    for(var i=0; i&lt;this.length; i++) {
        if(this[i] == val) {
            this.splice(i, 1);
            break;
        }
    }
}
//..

var somearray = [&quot;mon&quot;, &quot;tue&quot;, &quot;wed&quot;, &quot;thur&quot;]

somearray.removeByValue(&quot;tue&quot;);

//somearray will now have &quot;mon&quot;, &quot;wed&quot;, &quot;thur&quot;
</pre>
<p><iframe src="http://viralpatel.net/blogs/demo/js/javascript-tips/4.html" frameborder="0" width="100%" height="200px"></iframe></p>
<h2>5. Calling JavaScript function from String</h2>
<p>Sometime you want to call a Javascript method at runtime whos name you know. Let say there is a method &#8220;foo()&#8221; which you want to call at runtime. Below is a small JS snippet that helps you calling a method just by its name.</p>
<p>Reference: <a href="http://viralpatel.net/blogs/calling-javascript-function-from-string/" rel="nofollow">Call Function as String</a></p>
<pre class="brush: jscript; title: ; notranslate">
var strFun = &quot;someFunction&quot;; //Name of the function to be called
var strParam = &quot;this is the parameter&quot;; //Parameters to be passed in function
 
//Create the function
var fn = window[strFun];
 
//Call the function
fn(strParam);
</pre>
<p><iframe src="http://viralpatel.net/blogs/demo/js/javascript-tips/5.html" frameborder="0" width="100%" height="200px"></iframe></p>
<h2>6. Generate Random number from 1 to N</h2>
<p>Below little snippet helps you in generating random number between 1 to N. Might come handy for your next JS game.</p>
<pre class="brush: jscript; title: ; notranslate">
//random number from 1 to N
var random = Math.floor(Math.random() * N + 1);

//random number from 1 to 10
var random = Math.floor(Math.random() * 10 + 1);

//random number from 1 to 100
var random = Math.floor(Math.random() * 100 + 1);
</pre>
<p><iframe src="http://viralpatel.net/blogs/demo/js/javascript-tips/6.html" frameborder="0" width="100%" height="200px"></iframe></p>
<h2>7. Capture browser close button event or exiting the page in JavaScript</h2>
<p>This is a common use case. You want to capture the browsers close event so that you can alert user if there is any unsaved data on webpage that should be saved. Below javascript snippet will help you in that.</p>
<p>Reference: <a rel="nofollow" href="http://viralpatel.net/blogs/how-to-capture-browser-close-button-event-or-exiting-the-page-in-javascript/">Capture Browser Close Event</a></p>
<pre class="brush: jscript; title: ; notranslate">
&lt;script language=&quot;javascript&quot;&gt;
function fnUnloadHandler() {
       // Add your code here
       alert(&quot;Unload event.. Do something to invalidate users session..&quot;);
}
&lt;/script&gt;
&lt;body onbeforeunload=&quot;fnUnloadHandler()&quot;&gt;
    &lt;!-- Your page content --&gt;
&lt;/body&gt;
</pre>
<h2>8. Warn user if Back is pressed</h2>
<p>This is same as above. Difference is instead of capturing close event here we capture back button event. So that we know if user is moving awaw from this webpage.<br />
Reference: <a rel="nofollow" href="http://viralpatel.net/blogs/disable-back-button-browser-javascript/">Capture Browser Back Button</a></p>
<pre class="brush: jscript; title: ; notranslate">
window.onbeforeunload = function() { 
	return &quot;You work will be lost.&quot;; 
};
</pre>
<h2>9. Check if Form is Dirty</h2>
<p>A common usecase. You need to check if user changed anything in an HTML form. Below function <code>formIsDirty</code> returns a boolean value true or false depending on weather user modified something within the form.</p>
<pre class="brush: jscript; title: ; notranslate">
/**
 * Determines if a form is dirty by comparing the current value of each element
 * with its default value.
 *
 * @param {Form} form the form to be checked.
 * @return {Boolean} &lt;code&gt;true&lt;/code&gt; if the form is dirty, &lt;code&gt;false&lt;/code&gt;
 *                   otherwise.
 */
function formIsDirty(form) {
  for (var i = 0; i &lt; form.elements.length; i++) {
    var element = form.elements[i];
    var type = element.type;
    if (type == &quot;checkbox&quot; || type == &quot;radio&quot;) {
      if (element.checked != element.defaultChecked) {
        return true;
      }
    }
    else if (type == &quot;hidden&quot; || type == &quot;password&quot; ||
             type == &quot;text&quot; || type == &quot;textarea&quot;) {
      if (element.value != element.defaultValue) {
        return true;
      }
    }
    else if (type == &quot;select-one&quot; || type == &quot;select-multiple&quot;) {
      for (var j = 0; j &lt; element.options.length; j++) {
        if (element.options[j].selected !=
            element.options[j].defaultSelected) {
          return true;
        }
      }
    }
  }
  return false;
}
</pre>
<pre class="brush: jscript; title: ; notranslate">
window.onbeforeunload = function(e) {
  e = e || window.event;  
  if (formIsDirty(document.forms[&quot;someForm&quot;])) {
    // For IE and Firefox
    if (e) {
      e.returnValue = &quot;You have unsaved changes.&quot;;
    }
    // For Safari
    return &quot;You have unsaved changes.&quot;;
  }
};
</pre>
<p><iframe src="http://viralpatel.net/blogs/demo/js/javascript-tips/8.html" frameborder="0" width="100%" height="200px"></iframe></p>
<h2>10. Disable Back button using JavaScript</h2>
<p>This one is tricky. You want to disable the browsers back button (Dont ask me why!!). Below code snippet will let you do this. The only catch here is that you need to put this code in page where you dont want user to come back. See below reference for more details.<br />
Reference: <a rel="nofollow" href="http://viralpatel.net/blogs/disable-back-button-browser-javascript">Disable Browsers Back Button</a></p>
<pre class="brush: jscript; title: ; notranslate">
&lt;SCRIPT type=&quot;text/javascript&quot;&gt;
    window.history.forward();
    function noBack() { window.history.forward(); }
&lt;/SCRIPT&gt;
&lt;/HEAD&gt;
&lt;BODY onload=&quot;noBack();&quot;
    onpageshow=&quot;if (event.persisted) noBack();&quot; onunload=&quot;&quot;&gt;
</pre>
<h2>11. Deleting Multiple Values From Listbox in JavaScript</h2>
<p>You have a SELECT box. User can select multiple OPTIONS from this SELECT box and remove them. Below Javascript function <code>selectBoxRemove</code> let you do this. Just pass ID of SELECT object you want to remove OPTIONS in.</p>
<p>Reference: <a rel="nofollow" href="http://viralpatel.net/blogs/javascript-delete-multiple-values-options-listbox/">Delete Multiple Options in Select</a></p>
<pre class="brush: jscript; title: ; notranslate">
function selectBoxRemove(sourceID) {
 
    //get the listbox object from id.
    var src = document.getElementById(sourceID);
  
    //iterate through each option of the listbox
    for(var count= src.options.length-1; count &gt;= 0; count--) {
 
         //if the option is selected, delete the option
        if(src.options[count].selected == true) {
  
                try {
                         src.remove(count, null);
                         
                 } catch(error) {
                         
                         src.remove(count);
                }
        }
    }
}
</pre>
<p><iframe src="http://viralpatel.net/blogs/demo/js/javascript-tips/11.html" frameborder="0" width="100%" height="260px"></iframe></p>
<h2>12. Listbox Select All/Deselect All using JavaScript</h2>
<p>You can use below JS snippet to select/deselect all the OPTIONS from a SELECT box. Just pass the ID of select box you want to perform this operation on and also a boolean value <code>isSelect</code> specifying what operation you want to perform.<br />
Reference: <a rel="nofollow" href="http://viralpatel.net/blogs/listbox-select-all-move-left-right-up-down-javascript/">Select All/None using Javascript</a></p>
<pre class="brush: jscript; title: ; notranslate">
function listboxSelectDeselect(listID, isSelect) {
    var listbox = document.getElementById(listID);
    for(var count=0; count &lt; listbox.options.length; count++) {
            listbox.options[count].selected = isSelect;
    }
}
</pre>
<p><iframe src="http://viralpatel.net/blogs/demo/js/javascript-tips/12.html" frameborder="0" width="100%" height="270px"></iframe></p>
<h2>13. Listbox Move selected items Up / Down</h2>
<p>This one is useful if you are playing a lot with multi options select box in your application. This function let you move select OPTIONS in a SELECT box to UP or DOWN. See below reference for more details.<br />
Reference: <a rel="nofollow" href="http://viralpatel.net/blogs/listbox-select-all-move-left-right-up-down-javascript/">Move Up/Down Selected Items in a Listbox</a></p>
<pre class="brush: jscript; title: ; notranslate">
function listbox_move(listID, direction) {
 
    var listbox = document.getElementById(listID);
    var selIndex = listbox.selectedIndex;
 
    if(-1 == selIndex) {
        alert(&quot;Please select an option to move.&quot;);
        return;
    }
 
    var increment = -1;
    if(direction == 'up')
        increment = -1;
    else
        increment = 1;
 
    if((selIndex + increment) &lt; 0 ||
        (selIndex + increment) &gt; (listbox.options.length-1)) {
        return;
    }
 
    var selValue = listbox.options[selIndex].value;
    var selText = listbox.options[selIndex].text;
    listbox.options[selIndex].value = listbox.options[selIndex + increment].value
    listbox.options[selIndex].text = listbox.options[selIndex + increment].text
 
    listbox.options[selIndex + increment].value = selValue;
    listbox.options[selIndex + increment].text = selText;
 
    listbox.selectedIndex = selIndex + increment;
}
//..
//..

listbox_move('countryList', 'up'); //move up the selected option
listbox_move('countryList', 'down'); //move down the selected option
</pre>
<p><iframe src="http://viralpatel.net/blogs/demo/js/javascript-tips/13.html" frameborder="0" width="100%" height="260px"></iframe></p>
<h2>14. Listbox Move Left/Right Options</h2>
<p>This javascript function lets you move selected OPTIONS between two SELECT boxes. Check below reference for details.<br />
Reference: <a rel="nofollow" href="http://viralpatel.net/blogs/listbox-select-all-move-left-right-up-down-javascript/">Move Options Left/Right between two SELECT boxes</a></p>
<pre class="brush: jscript; title: ; notranslate">
function listbox_moveacross(sourceID, destID) {
    var src = document.getElementById(sourceID);
    var dest = document.getElementById(destID);
 
    for(var count=0; count &lt; src.options.length; count++) {
 
        if(src.options[count].selected == true) {
                var option = src.options[count];
 
                var newOption = document.createElement(&quot;option&quot;);
                newOption.value = option.value;
                newOption.text = option.text;
                newOption.selected = true;
                try {
                         dest.add(newOption, null); //Standard
                         src.remove(count, null);
                 }catch(error) {
                         dest.add(newOption); // IE only
                         src.remove(count);
                 }
                count--;
        }
    }
}
//..
//..

listbox_moveacross('countryList', 'selectedCountryList');
</pre>
<p><iframe src="http://viralpatel.net/blogs/demo/js/javascript-tips/14.html" frameborder="0" width="100%" height="260px"></iframe></p>
<h2>15. Initialize JavaScript Array with series of numbers</h2>
<p>Sometime you want to initialize a Javascript array with series of numbers. Below code snippet will let you achieve this. This will initialiaze array <code>numbers</code> with numbers 1 to 100.</p>
<pre class="brush: jscript; title: ; notranslate">
var numbers = [];
for(var i=1; numbers.push(i++)&lt;100;);
//numbers = [0,1,2,3 ... 100]
</pre>
<p><iframe src="http://viralpatel.net/blogs/demo/js/javascript-tips/15.html" frameborder="0" width="100%" height="200px"></iframe></p>
<h2>16. Rounding Numbers to &#8216;N&#8217; Decimals</h2>
<p>This one is quite useful. It will let you round off a number to &#8216;N&#8217; decimal places. Here in below example we are rounding of a number to 2 decimal places.</p>
<pre class="brush: jscript; title: ; notranslate">
var num = 2.443242342;
alert(num.toFixed(2)); // 2.44
</pre>
<p>Note that we use <code>toFixed()</code> method here. <code>toFixed(n)</code> provides n length after the decimal point; whereas <code>toPrecision(x)</code> provides x total length. </p>
<pre class="brush: jscript; title: ; notranslate">
num = 500.2349;
result = num.toPrecision(4); // result will equal 500.2
</pre>
<p><iframe src="http://viralpatel.net/blogs/demo/js/javascript-tips/16.html" frameborder="0" width="100%" height="200px"></iframe></p>
<h2>17. Check if String contains another substring in JavaScript</h2>
<p>Below code snippet (courtesy Stackoverflow) let you check if a given string contains another substring. </p>
<p>Reference: <a rel="nofollow" href="http://stackoverflow.com/questions/1789945/method-like-string-contains-in-javascript">stackoverflow</a></p>
<pre class="brush: jscript; title: ; notranslate">
if (!Array.prototype.indexOf) { 
    Array.prototype.indexOf = function(obj, start) {
         for (var i = (start || 0), j = this.length; i &lt; j; i++) {
             if (this[i] === obj) { return i; }
         }
         return -1;
    }
}

if (!String.prototype.contains) {
    String.prototype.contains = function (arg) {
        return !!~this.indexOf(arg);
    };
}
</pre>
<p>The code will add two new methods to String, <code>indexOf</code> and <code>contains</code>. Once this is done, you can use contains method to check weather a substring is present in a given string.</p>
<p>var hay = &quot;a quick brown fox jumps over lazy dog&quot;;<br />
var needle = &quot;jumps&quot;;<br />
alert(hay.contains(needle));</p>
<p><iframe src="http://viralpatel.net/blogs/demo/js/javascript-tips/17.html" frameborder="0" width="100%" height="200px"></iframe></p>
<h2>18. Remove Duplicates from JavaScript Array</h2>
<p>Aha!! You know this one comes quite handy. Just call removeDuplicates method and pass the array, it should remove all duplicate elements from the array.</p>
<pre class="brush: jscript; title: ; notranslate">
function removeDuplicates(arr) {
	var temp = {};
	for (var i = 0; i &lt; arr.length; i++)
		temp[arr[i]] = true;

	var r = [];
	for (var k in temp)
		r.push(k);
	return r;
}

//Usage
var fruits = ['apple', 'orange', 'peach', 'apple', 'strawberry', 'orange'];
var uniquefruits = removeDuplicates(fruits);
//print uniquefruits ['apple', 'orange', 'peach', 'strawberry'];
</pre>
<p><iframe src="http://viralpatel.net/blogs/demo/js/javascript-tips/18.html" frameborder="0" width="100%" height="200px"></iframe></p>
<h2>19. Trim a String in JavaScript</h2>
<p>Below code will add a method trim() to String which can be used to remove spaces from both sides of a string.</p>
<pre class="brush: jscript; title: ; notranslate">
if (!String.prototype.trim) {
   String.prototype.trim=function() {
   	return this.replace(/^\s+|\s+$/g, '');
   };
}

//usage
var str = &quot;  some string    &quot;;
str.trim();
//print str = &quot;some string&quot;
</pre>
<p><iframe src="http://viralpatel.net/blogs/demo/js/javascript-tips/19.html" frameborder="0" width="100%" height="200px"></iframe></p>
<h2>20. Redirect webpage in JavaScript</h2>
<p>This javascript code should perform http redirect on a given URL.</p>
<pre class="brush: jscript; title: ; notranslate">
window.location.href = &quot;http://viralpatel.net&quot;;
</pre>
<h2>21. Encode a URL in JavaScript</h2>
<p>Whenever you are making an http request and passing some parameters. You should encode the URL string. Use encodeURIComponent function for encoding a url parameter.<br />
Reference: <a rel="nofollow" href="http://www.w3schools.com/jsref/jsref_encodeuricomponent.asp">w3scools</a></p>
<pre class="brush: jscript; title: ; notranslate">
var myOtherUrl = 
       &quot;http://example.com/index.html?url=&quot; + encodeURIComponent(myUrl);
</pre>
<p><iframe src="http://viralpatel.net/blogs/demo/js/javascript-tips/21.html" frameborder="0" width="100%" height="200px"></iframe></p>
<div class='yarpp-related-rss'>
<h3>Related Posts</h3><ol>
<li><a href='http://viralpatel.net/blogs/listbox-select-all-move-left-right-up-down-javascript/' rel='bookmark' title='Listbox options javascript select all,move left-right, move up-down'>Listbox options javascript select all,move left-right, move up-down</a></li>
<li><a href='http://viralpatel.net/blogs/javascript-array-remove-element-js-array-delete-element/' rel='bookmark' title='JavaScript Array Remove an Element'>JavaScript Array Remove an Element</a></li>
<li><a href='http://viralpatel.net/blogs/javascript-delete-multiple-values-options-listbox/' rel='bookmark' title='Deleting Multiple Values From Listbox in JavaScript'>Deleting Multiple Values From Listbox in JavaScript</a></li>
<li><a href='http://viralpatel.net/blogs/20-top-jquery-tips-tricks-for-jquery-programmers/' rel='bookmark' title='20 Top jQuery Tips &amp; Tricks for jQuery Programmers'>20 Top jQuery Tips &#038; Tricks for jQuery Programmers</a></li>
<li><a href='http://viralpatel.net/blogs/dynamic-add-textbox-input-button-radio-element-html-javascript/' rel='bookmark' title='Dynamically add button, textbox, input, radio elements in html form using JavaScript.'>Dynamically add button, textbox, input, radio elements in html form using JavaScript.</a></li>
<li><a href='http://viralpatel.net/blogs/dynamic-combobox-listbox-drop-down-using-javascript/' rel='bookmark' title='Dynamic combobox-listbox-drop-down using javascript'>Dynamic combobox-listbox-drop-down using javascript</a></li>
<li><a href='http://viralpatel.net/blogs/javascript-multiple-selection-listbox-problem-ms-internet-explorer/' rel='bookmark' title='Multiple Selection Listbox Javascript Problem in MS Internet Explorer'>Multiple Selection Listbox Javascript Problem in MS Internet Explorer</a></li>
</ol>
</div>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=7Txp1SIlKas:xbV3nzYzJuU:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=7Txp1SIlKas:xbV3nzYzJuU:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=7Txp1SIlKas:xbV3nzYzJuU:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?i=7Txp1SIlKas:xbV3nzYzJuU:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=7Txp1SIlKas:xbV3nzYzJuU:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=7Txp1SIlKas:xbV3nzYzJuU:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=I9og5sOYxJI" border="0"></img></a>
</div>]]></content:encoded>
			<wfw:commentRss>http://viralpatel.net/blogs/javascript-tips-tricks/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://viralpatel.net/blogs/javascript-tips-tricks/</feedburner:origLink></item>
		<item>
		<title>CSS Styling Radio Button and Checkboxes</title>
		<link>http://feedproxy.google.com/~r/viralpatelnet/~3/3FGhWfxx4Gc/</link>
		<comments>http://viralpatel.net/blogs/css-radio-button-checkbox-background/#comments</comments>
		<pubDate>Mon, 13 May 2013 14:29:42 +0000</pubDate>
		<dc:creator>Viral Patel</dc:creator>
				<category><![CDATA[CSS]]></category>

		<guid isPermaLink="false">http://viralpatel.net/blogs/?p=3039</guid>
		<description><![CDATA[The idea is simple. We want to change the look and feel of existing radio buttons into more of a push button. The above image pretty much tells what we want to achieve. Now we want to do this without using Javascript or JQuery. Just plain HTML and CSS. Nothing fancy. Lets dive into code. [...]<div class='yarpp-related-rss'>
<h3>Related Posts</h3><ol>
<li><a href='http://viralpatel.net/blogs/dynamic-add-textbox-input-button-radio-element-html-javascript/' rel='bookmark' title='Dynamically add button, textbox, input, radio elements in html form using JavaScript.'>Dynamically add button, textbox, input, radio elements in html form using JavaScript.</a></li>
<li><a href='http://viralpatel.net/blogs/firefox-3-6-released-css-gradient-feature/' rel='bookmark' title='Firefox 3.6 Released: With New CSS Gradient Feature'>Firefox 3.6 Released: With New CSS Gradient Feature</a></li>
<li><a href='http://viralpatel.net/blogs/textbox-with-background-image-using-css/' rel='bookmark' title='Textbox with background image using CSS'>Textbox with background image using CSS</a></li>
<li><a href='http://viralpatel.net/blogs/20-very-useful-css-stylesheet-tips-tricks/' rel='bookmark' title='20 Very Useful CSS Stylesheet Tips &amp; Tricks'>20 Very Useful CSS Stylesheet Tips &#038; Tricks</a></li>
<li><a href='http://viralpatel.net/blogs/default-text-label-textbox-javascript-jquery/' rel='bookmark' title='Default Text Label in Textbox using JavaScript/jQuery'>Default Text Label in Textbox using JavaScript/jQuery</a></li>
<li><a href='http://viralpatel.net/blogs/change-form-input-textbox-style-focus-jquery/' rel='bookmark' title='Changing Form Input (Textbox) Style on Focus using jQuery'>Changing Form Input (Textbox) Style on Focus using jQuery</a></li>
<li><a href='http://viralpatel.net/blogs/how-much-im-feeling-lucky-button-cost-google/' rel='bookmark' title='How much does the &#8220;I&#8217;m feeling lucky&#8221; button cost Google?'>How much does the &#8220;I&#8217;m feeling lucky&#8221; button cost Google?</a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/2013/05/radio-button-css-style.png" alt="radio-button-css-style" width="262" height="132" class="aligncenter size-full wp-image-3041" /><br />
The idea is simple. We want to change the look and feel of existing radio buttons into more of a push button. The above image pretty much tells what we want to achieve.</p>
<p>Now we want to do this without using <a href="http://viralpatel.net/blogs/category/javascript/">Javascript</a> or <a href="http://viralpatel.net/blogs/category/jquery/">JQuery</a>. Just plain HTML and CSS. Nothing fancy.</p>
<p>Lets dive into code.</p>
<h2>1. The HTML</h2>
<p>The HTML should looks pretty much like HTML. Nothing fancy here either. Just a bunch of radiobuttons following by labels. </p>
<pre class="brush: xml; title: ; notranslate">
    &lt;input type=&quot;radio&quot; id=&quot;radio1&quot; name=&quot;radios&quot; value=&quot;all&quot; checked&gt;
       &lt;label for=&quot;radio1&quot;&gt;iPhone&lt;/label&gt;
    &lt;input type=&quot;radio&quot; id=&quot;radio2&quot; name=&quot;radios&quot;value=&quot;false&quot;&gt;
       &lt;label for=&quot;radio2&quot;&gt;Galaxy S IV&lt;/label&gt;
    &lt;input type=&quot;radio&quot; id=&quot;radio3&quot; name=&quot;radios&quot; value=&quot;true&quot;&gt;
       &lt;label for=&quot;radio3&quot;&gt;Nexus S&lt;/label&gt; 
</pre>
<h2>2. The CSS</h2>
<p>Now the magic is in CSS. We want to change the look n feel of traditional radiobuttons into sexy pushbuttons.</p>
<p>Before we see the CSS, lets check one important CSS selector which you might not know already. It is called <a href="http://www.w3.org/TR/CSS2/selector.html#adjacent-selectors">Adjacent sibling selectors</a>. The idea is to select an element next to another element using syntax E1 + E2. So if I write a CSS code like:</p>
<pre class="brush: css; title: ; notranslate">
div + p {
     color: red;
} 
</pre>
<p>This should select only those <code>&lt;p&gt;</code> elements which are adjacent (i.e. next to) <code>&lt;div&gt;</code> tags! This can come handy in lot of scenarios when you want to apply certain style to element based on their sequence.</p>
<p>So now we got the idea and know how Adjacent selector is used, lets apply that in our problem at hand. </p>
<pre class="brush: css; title: ; notranslate">
/*
  Hide radio button (the round disc)
  we will use just the label to create pushbutton effect
*/
input[type=radio] {
    display:none; 
    margin:10px;
}

/*
  Change the look'n'feel of labels (which are adjacent to radiobuttons).
  Add some margin, padding to label
*/
input[type=radio] + label {
    display:inline-block;
    margin:-2px;
    padding: 4px 12px;
    background-color: #e7e7e7;
    border-color: #ddd;
}
/*
 Change background color for label next to checked radio button
 to make it look like highlighted button
*/
input[type=radio]:checked + label { 
   background-image: none;
    background-color:#d0d0d0;
}
</pre>
<h3>Demo</h3>
<p><iframe src="http://viralpatel.net/blogs/demo/css/radio-checkbox-background/css-radio-button-background-change.html" frameborder="0" width="100%" height="120px"></iframe><br />
JSFiddle: <a rel="nofollow" target="_new" href="http://jsfiddle.net/viralpatel/p499h/">http://jsfiddle.net/viralpatel/p499h/</a></p>
<p>Voilla!! That works!! Although they look different, these are basically radiobuttons at heart. You can create forms using these buttons and on submit, can handle values at server side as normal radiobuttons. No Javascript, no jquery hacks.. </p>
<h3>3. More CSS</h3>
<p>Lets add some more style to these radiobuttons and make them look more pushbutton&#8217;ish. Style courtesy <a href="http://twitter.github.io/bootstrap/" target="_new" rel="nofollow">Twitter Bootstrap</a> <img src='http://viralpatel.net/blogs/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<pre class="brush: css; title: ; notranslate">
	input[type=radio] {
		display:none;
	}

	input[type=radio] + label {
		display:inline-block;
		margin:-2px;
		padding: 4px 12px;
		margin-bottom: 0;
		font-size: 14px;
		line-height: 20px;
		color: #333;
		text-align: center;
		text-shadow: 0 1px 1px rgba(255,255,255,0.75);
		vertical-align: middle;
		cursor: pointer;
		background-color: #f5f5f5;
		background-image: -moz-linear-gradient(top,#fff,#e6e6e6);
		background-image: -webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));
		background-image: -webkit-linear-gradient(top,#fff,#e6e6e6);
		background-image: -o-linear-gradient(top,#fff,#e6e6e6);
		background-image: linear-gradient(to bottom,#fff,#e6e6e6);
		background-repeat: repeat-x;
		border: 1px solid #ccc;
		border-color: #e6e6e6 #e6e6e6 #bfbfbf;
		border-color: rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);
		border-bottom-color: #b3b3b3;
		filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);
		filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);
		-webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);
		-moz-box-shadow: inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);
		box-shadow: inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);
	}

	input[type=radio]:checked + label {
		   background-image: none;
		outline: 0;
		-webkit-box-shadow: inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);
		-moz-box-shadow: inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);
		box-shadow: inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);
			background-color:#e0e0e0;
	}
</pre>
<h3>Demo</h3>
<p><iframe src="http://viralpatel.net/blogs/demo/css/radio-checkbox-background/css-radiobutton.html" frameborder="0" width="100%" height="120px"></iframe><br />
JSFiddle: <a rel="nofollow" target="_new" href="http://jsfiddle.net/viralpatel/p499h/">http://jsfiddle.net/viralpatel/p499h/</a></p>
<h2>The Checkboxes</h2>
<p>Same technique can be applied on checkboxes. Just replace <code>type=radio</code> with <code>type=checkbox</code> in above CSS and see how normal looking html checkbox changes into pushbutton checkbox.</p>
<h2>Demo</h2>
<p><iframe src="http://viralpatel.net/blogs/demo/css/radio-checkbox-background/css-checkboxe-background.html" frameborder="0" width="100%" height="120px"></iframe></p>
<p>The code is available on JSFiddle.<br />
<b>Play on JSFiddle:</b> <a rel="nofollow" target="_new" href="http://jsfiddle.net/viralpatel/p499h/">http://jsfiddle.net/viralpatel/p499h/</a></p>
<div class='yarpp-related-rss'>
<h3>Related Posts</h3><ol>
<li><a href='http://viralpatel.net/blogs/dynamic-add-textbox-input-button-radio-element-html-javascript/' rel='bookmark' title='Dynamically add button, textbox, input, radio elements in html form using JavaScript.'>Dynamically add button, textbox, input, radio elements in html form using JavaScript.</a></li>
<li><a href='http://viralpatel.net/blogs/firefox-3-6-released-css-gradient-feature/' rel='bookmark' title='Firefox 3.6 Released: With New CSS Gradient Feature'>Firefox 3.6 Released: With New CSS Gradient Feature</a></li>
<li><a href='http://viralpatel.net/blogs/textbox-with-background-image-using-css/' rel='bookmark' title='Textbox with background image using CSS'>Textbox with background image using CSS</a></li>
<li><a href='http://viralpatel.net/blogs/20-very-useful-css-stylesheet-tips-tricks/' rel='bookmark' title='20 Very Useful CSS Stylesheet Tips &amp; Tricks'>20 Very Useful CSS Stylesheet Tips &#038; Tricks</a></li>
<li><a href='http://viralpatel.net/blogs/default-text-label-textbox-javascript-jquery/' rel='bookmark' title='Default Text Label in Textbox using JavaScript/jQuery'>Default Text Label in Textbox using JavaScript/jQuery</a></li>
<li><a href='http://viralpatel.net/blogs/change-form-input-textbox-style-focus-jquery/' rel='bookmark' title='Changing Form Input (Textbox) Style on Focus using jQuery'>Changing Form Input (Textbox) Style on Focus using jQuery</a></li>
<li><a href='http://viralpatel.net/blogs/how-much-im-feeling-lucky-button-cost-google/' rel='bookmark' title='How much does the &#8220;I&#8217;m feeling lucky&#8221; button cost Google?'>How much does the &#8220;I&#8217;m feeling lucky&#8221; button cost Google?</a></li>
</ol>
</div>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=3FGhWfxx4Gc:KEyqd3gwKEM:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=3FGhWfxx4Gc:KEyqd3gwKEM:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=3FGhWfxx4Gc:KEyqd3gwKEM:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?i=3FGhWfxx4Gc:KEyqd3gwKEM:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=3FGhWfxx4Gc:KEyqd3gwKEM:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=3FGhWfxx4Gc:KEyqd3gwKEM:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=I9og5sOYxJI" border="0"></img></a>
</div>]]></content:encoded>
			<wfw:commentRss>http://viralpatel.net/blogs/css-radio-button-checkbox-background/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://viralpatel.net/blogs/css-radio-button-checkbox-background/</feedburner:origLink></item>
		<item>
		<title>Java XPath Tutorial: How to Parse XML File using XPath in Java</title>
		<link>http://feedproxy.google.com/~r/viralpatelnet/~3/1OHn3ztfXSc/</link>
		<comments>http://viralpatel.net/blogs/java-xml-xpath-tutorial-parse-xml/#comments</comments>
		<pubDate>Mon, 13 May 2013 09:47:04 +0000</pubDate>
		<dc:creator>Viral Patel</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[reading xml]]></category>
		<category><![CDATA[xml]]></category>
		<category><![CDATA[xml-parsing]]></category>

		<guid isPermaLink="false">http://viralpatel.net/blogs/?p=3008</guid>
		<description><![CDATA[XPath is a language for finding information in an XML file. You can say that XPath is (sort of) SQL for XML files. XPath is used to navigate through elements and attributes in an XML document. You can also use XPath to traverse through an XML file in Java. XPath comes with powerful expressions that [...]<div class='yarpp-related-rss'>
<h3>Related Posts</h3><ol>
<li><a href='http://viralpatel.net/blogs/parsing-reading-xml-file-in-java-xml-reading-java-tutorial/' rel='bookmark' title='Parsing / Reading XML file in Java.'>Parsing / Reading XML file in Java.</a></li>
<li><a href='http://viralpatel.net/blogs/20-useful-java-code-snippets-for-java-developers/' rel='bookmark' title='20 very useful Java code snippets for Java Developers'>20 very useful Java code snippets for Java Developers</a></li>
<li><a href='http://viralpatel.net/blogs/java-load-csv-file-to-database/' rel='bookmark' title='Java: How to Load CSV file into Database'>Java: How to Load CSV file into Database</a></li>
<li><a href='http://viralpatel.net/blogs/decompile-class-file-java-decompiler-class-java-class/' rel='bookmark' title='Decompile Java Class file using decompilers.'>Decompile Java Class file using decompilers.</a></li>
<li><a href='http://viralpatel.net/blogs/hibernate-one-to-one-mapping-tutorial-using-annotation/' rel='bookmark' title='Hibernate One To One Annotation Mapping Tutorial'>Hibernate One To One Annotation Mapping Tutorial</a></li>
<li><a href='http://viralpatel.net/blogs/java-read-write-excel-file-apache-poi/' rel='bookmark' title='Read / Write Excel file in Java using Apache POI'>Read / Write Excel file in Java using Apache POI</a></li>
<li><a href='http://viralpatel.net/blogs/hibernate-one-to-many-xml-mapping-tutorial/' rel='bookmark' title='Hibernate One To Many XML Mapping Tutorial'>Hibernate One To Many XML Mapping Tutorial</a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>XPath is a language for finding information in an XML file. You can say that XPath is (sort of) SQL for XML files. XPath is used to navigate through elements and attributes in an XML document. You can also use XPath to <a href="http://viralpatel.net/blogs/parsing-reading-xml-file-in-java-xml-reading-java-tutorial/">traverse through an XML file in Java</a>.</p>
<p>XPath comes with powerful expressions that can be used to parse an xml document and retrieve relevant information.</p>
<p>For demo, let us consider an xml file that holds information of employees.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot;?&gt;
&lt;Employees&gt;
	&lt;Employee emplid=&quot;1111&quot; type=&quot;admin&quot;&gt;
		&lt;firstname&gt;John&lt;/firstname&gt;
		&lt;lastname&gt;Watson&lt;/lastname&gt;
		&lt;age&gt;30&lt;/age&gt;
		&lt;email&gt;johnwatson@sh.com&lt;/email&gt;
	&lt;/Employee&gt;
	&lt;Employee emplid=&quot;2222&quot; type=&quot;admin&quot;&gt;
		&lt;firstname&gt;Sherlock&lt;/firstname&gt;
		&lt;lastname&gt;Homes&lt;/lastname&gt;
		&lt;age&gt;32&lt;/age&gt;
		&lt;email&gt;sherlock@sh.com&lt;/email&gt;
	&lt;/Employee&gt;
	&lt;Employee emplid=&quot;3333&quot; type=&quot;user&quot;&gt;
		&lt;firstname&gt;Jim&lt;/firstname&gt;
		&lt;lastname&gt;Moriarty&lt;/lastname&gt;
		&lt;age&gt;52&lt;/age&gt;
		&lt;email&gt;jim@sh.com&lt;/email&gt;
	&lt;/Employee&gt;
	&lt;Employee emplid=&quot;4444&quot; type=&quot;user&quot;&gt;
		&lt;firstname&gt;Mycroft&lt;/firstname&gt;
		&lt;lastname&gt;Holmes&lt;/lastname&gt;
		&lt;age&gt;41&lt;/age&gt;
		&lt;email&gt;mycroft@sh.com&lt;/email&gt;
	&lt;/Employee&gt;
&lt;/Employees&gt;</pre>
<p>I have saved this file at path <code>C:\employees.xml</code>. We will use this xml file in our demo and will try to fetch useful information using XPath. Before we start lets check few facts from above xml file.</p>
<ol>
<li>There are 4 employees in our xml file</li>
<li>Each employee has a unique employee id defined by attribute <code>emplid</code></li>
<li>Each employee also has an attribute <code>type</code> which defines whether an employee is admin or user.</li>
<li>Each employee has four child nodes: <code>firstname</code>, <code>lastname</code>, <code>age</code> and <code>email</code></li>
<li>Age is a number</li>
</ol>
<p>Let&#8217;s get started&#8230;</p>
<h2>1. Learning Java DOM Parsing API</h2>
<p>In order to understand XPath, first we need to understand basics of DOM parsing in Java. Java provides powerful implementation of domparser in form of below API. </p>
<h3>1.1 Creating a Java DOM XML Parser</h3>
<p>First, we need to create a document builder using <code>DocumentBuilderFactory</code> class. Just follow the code. It&#8217;s pretty much self explainatory. </p>
<pre class="brush: java; title: ; notranslate">
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
//...

DocumentBuilderFactory builderFactory =
        DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
    builder = builderFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
    e.printStackTrace();  
}
</pre>
<h3>1.2 Parsing XML with a Java DOM Parser</h3>
<p>Once we have a document builder object. We uses it to parse XML file and create a document object.</p>
<pre class="brush: java; title: ; notranslate">
import org.w3c.dom.Document;
import java.io.IOException;
import org.xml.sax.SAXException;
//...

try {
    Document document = builder.parse(
            new FileInputStream(&quot;c:\\employees.xml&quot;));
} catch (SAXException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
</pre>
<p>In above code, we are parsing an XML file from filesystem. Sometimes you might want to parse XML specified as String value instead of reading it from file. Below code comes handy to parse XML specified as String.</p>
<pre class="brush: java; title: ; notranslate">
String xml = ...;
Document xmlDocument = builder.parse(new ByteArrayInputStream(xml.getBytes()));
</pre>
<h3>1.3 Creating an XPath object</h3>
<p>Once we have document object. We are ready to use XPath. Just create an xpath object using XPathFactory.</p>
<pre class="brush: java; title: ; notranslate">
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
//...

XPath xPath =  XPathFactory.newInstance().newXPath();
</pre>
<h3>1.4 Using XPath to parse the XML</h3>
<p>Use xpath object to complie an XPath expression and evaluate it on document. In below code we read email address of employee having employee id = 3333. Also we have specified APIs to read an XML node and a nodelist.</p>
<pre class="brush: java; title: ; notranslate">
String expression = &quot;/Employees/Employee[@emplid='3333']/email&quot;;

//read a string value
String email = xPath.compile(expression).evaluate(xmlDocument);

//read an xml node using xpath
Node node = (Node) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODE);

//read a nodelist using xpath
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
</pre>
<h2>2. Learning XPath Expressions</h2>
<p>As mentioned above, XPath uses a path expression to select nodes or list of node from an xml document. Heres a list of useful paths and expression that can be used to select any node/nodelist from an xml document.</p>
<table>
<tr>
<th>Expression</th>
<th>Description</th>
</tr>
<tr>
<td><code>nodename</code></td>
<td>Selects all nodes with the name <em>&#8220;nodename&#8221;</em></td>
</tr>
<tr>
<td><code>/</code></td>
<td>Selects from the root node</td>
</tr>
<tr>
<td><code>//</code></td>
<td>Selects nodes in the document from the current node that match the selection no matter where they are</td>
</tr>
<tr>
<td><code>.</code></td>
<td>Selects the current node</td>
</tr>
<tr>
<td><code>..</code></td>
<td>Selects the parent of the current node</td>
</tr>
<tr>
<td><code>@</code></td>
<td>Selects attributes</td>
</tr>
<tr>
<td><code>employee</code></td>
<td>Selects all nodes with the name &#8220;employee&#8221;</td>
</tr>
<tr>
<td><code>employees/employee</code></td>
<td>Selects all employee elements that are children of employees</td>
</tr>
<tr>
<td><code>//employee</code></td>
<td>Selects all book elements no matter where they are in the document</td>
</tr>
</table>
<p>Below list of expressions are called <strong>Predicates</strong>. The Predicates are defined in square brackets [ ... ]. They are used to find a specific node or a node that contains a specific value.</p>
<table>
<tr>
<th>Path Expression</th>
<th>Result</th>
</tr>
<tr>
<td><code>/employees/employee[1]</code></td>
<td>Selects the first employee element that is the child of the employees element.</td>
</tr>
<tr>
<td><code>/employees/employee[last()]</code></td>
<td>Selects the last employee element that is the child of the employees element</td>
</tr>
<tr>
<td><code>/employees/employee[last()-1]</code></td>
<td>Selects the last but one employee element that is the child of the employees element</td>
</tr>
<tr>
<td><code>//employee[@type='admin']</code></td>
<td>Selects all the employee elements that have an attribute named type with a value of &#8216;admin&#8217;</td>
</tr>
</table>
<p>There are other useful expressions that you can use to query the data. </p>
<p>Read this w3school page for more details: <a href="http://www.w3schools.com/xpath/xpath_syntax.asp" target="_new" rel="nofollow">http://www.w3schools.com/xpath/xpath_syntax.asp</a></p>
<h2>3. Examples: Query XML document using XPath</h2>
<p>Below are few examples of using different expressions of xpath to fetch some information from xml document.</p>
<h3>3.1 Read firstname of all employees</h3>
<p>Below expression will read <code>firstname</code> of all the employees.</p>
<pre class="brush: java; title: ; notranslate">
String expression = &quot;/Employees/Employee/firstname&quot;;
System.out.println(expression);
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i &lt; nodeList.getLength(); i++) {
    System.out.println(nodeList.item(i).getFirstChild().getNodeValue()); 
}
</pre>
<p>Output:</p>
<pre class="brush: plain; title: ; notranslate">
John
Sherlock
Jim
Mycroft
</pre>
<h3>3.2 Read a specific employee using employee id</h3>
<p>Below expression will read employee information for employee with emplid = 2222. Check how we used API to retrieve node information and then traveresed this node to print xml tag and its value.</p>
<pre class="brush: java; title: ; notranslate">
String expression = &quot;/Employees/Employee[@emplid='2222']&quot;;
System.out.println(expression);
Node node = (Node) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODE);
if(null != node) {
	nodeList = node.getChildNodes();
	for (int i = 0;null!=nodeList &amp;&amp; i &lt; nodeList.getLength(); i++) {
		Node nod = nodeList.item(i);
		if(nod.getNodeType() == Node.ELEMENT_NODE)
			System.out.println(nodeList.item(i).getNodeName() + &quot; : &quot; + nod.getFirstChild().getNodeValue()); 
	}
}
</pre>
<p>Output:</p>
<pre class="brush: plain; title: ; notranslate">
firstname : Sherlock
lastname : Homes
age : 32
email : sherlock@sh.com
</pre>
<h3>3.3 Read firstname of all employees who are admin</h3>
<p>This is again a predicate example to read <code>firstname</code> of all employee who are admin (defined by type=admin).</p>
<pre class="brush: java; title: ; notranslate">
String expression = &quot;/Employees/Employee[@type='admin']/firstname&quot;;
System.out.println(expression);
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i &lt; nodeList.getLength(); i++) {
    System.out.println(nodeList.item(i).getFirstChild().getNodeValue()); 
}
</pre>
<p>Output:</p>
<pre class="brush: plain; title: ; notranslate">
John
Sherlock
</pre>
<h3>3.4 Read firstname of all employees who are older than 40 year</h3>
<p>See how we used predicate to filter employees who has <code>age &gt; 40</code>. </p>
<pre class="brush: java; title: ; notranslate">
String expression = &quot;/Employees/Employee[age&gt;40]/firstname&quot;;
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i &lt; nodeList.getLength(); i++) {
    System.out.println(nodeList.item(i).getFirstChild().getNodeValue()); 
}
</pre>
<p>Output:</p>
<pre class="brush: plain; title: ; notranslate">
Jim
Mycroft
</pre>
<h3>3.5 Read firstname of first two employees (defined in xml file)</h3>
<p>Within predicates, you can use <code>position()</code> to identify the position of xml element. Here we are filtering first two employees using position().</p>
<pre class="brush: java; title: ; notranslate">
String expression = &quot;/Employees/Employee[position() &lt;= 2]/firstname&quot;;
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i &lt; nodeList.getLength(); i++) {
    System.out.println(nodeList.item(i).getFirstChild().getNodeValue()); 
}
</pre>
<p>Output:</p>
<pre class="brush: plain; title: ; notranslate">
John
Sherlock
</pre>
<h2>4. Complete Java source code</h2>
<p>In order to execute this source, just create a basic Java project in your IDE or just save below code in Main.java and execute. It will need <code>employees.xml</code> file as input. Copy the employee xml defined in start of this tutorial at <code>c:\\employees.xml</code>.</p>
<pre class="brush: java; title: ; notranslate">
package net.viralpatel.java;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class Main {
	public static void main(String[] args) {

		try {
			FileInputStream file = new FileInputStream(new File(&quot;c:/employees.xml&quot;));
				
			DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
			
			DocumentBuilder builder =  builderFactory.newDocumentBuilder();
			
			Document xmlDocument = builder.parse(file);

			XPath xPath =  XPathFactory.newInstance().newXPath();

			System.out.println(&quot;*************************&quot;);
			String expression = &quot;/Employees/Employee[@emplid='3333']/email&quot;;
			System.out.println(expression);
			String email = xPath.compile(expression).evaluate(xmlDocument);
			System.out.println(email);

			System.out.println(&quot;*************************&quot;);
			expression = &quot;/Employees/Employee/firstname&quot;;
			System.out.println(expression);
			NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
			for (int i = 0; i &lt; nodeList.getLength(); i++) {
			    System.out.println(nodeList.item(i).getFirstChild().getNodeValue()); 
			}

			System.out.println(&quot;*************************&quot;);
			expression = &quot;/Employees/Employee[@type='admin']/firstname&quot;;
			System.out.println(expression);
			nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
			for (int i = 0; i &lt; nodeList.getLength(); i++) {
			    System.out.println(nodeList.item(i).getFirstChild().getNodeValue()); 
			}

			System.out.println(&quot;*************************&quot;);
			expression = &quot;/Employees/Employee[@emplid='2222']&quot;;
			System.out.println(expression);
			Node node = (Node) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODE);
			if(null != node) {
				nodeList = node.getChildNodes();
				for (int i = 0;null!=nodeList &amp;&amp; i &lt; nodeList.getLength(); i++) {
					Node nod = nodeList.item(i);
					if(nod.getNodeType() == Node.ELEMENT_NODE)
						System.out.println(nodeList.item(i).getNodeName() + &quot; : &quot; + nod.getFirstChild().getNodeValue()); 
				}
			}
			
			System.out.println(&quot;*************************&quot;);

			expression = &quot;/Employees/Employee[age&gt;40]/firstname&quot;;
			nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
			System.out.println(expression);
			for (int i = 0; i &lt; nodeList.getLength(); i++) {
			    System.out.println(nodeList.item(i).getFirstChild().getNodeValue()); 
			}
		
			System.out.println(&quot;*************************&quot;);
			expression = &quot;/Employees/Employee[1]/firstname&quot;;
			System.out.println(expression);
			nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
			for (int i = 0; i &lt; nodeList.getLength(); i++) {
			    System.out.println(nodeList.item(i).getFirstChild().getNodeValue()); 
			}
			System.out.println(&quot;*************************&quot;);
			expression = &quot;/Employees/Employee[position() &lt;= 2]/firstname&quot;;
			System.out.println(expression);
			nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
			for (int i = 0; i &lt; nodeList.getLength(); i++) {
			    System.out.println(nodeList.item(i).getFirstChild().getNodeValue()); 
			}

			System.out.println(&quot;*************************&quot;);
			expression = &quot;/Employees/Employee[last()]/firstname&quot;;
			System.out.println(expression);
			nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
			for (int i = 0; i &lt; nodeList.getLength(); i++) {
			    System.out.println(nodeList.item(i).getFirstChild().getNodeValue()); 
			}

			System.out.println(&quot;*************************&quot;);

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		}		
	}
}
</pre>
<p>That&#8217;s all folks <img src='http://viralpatel.net/blogs/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<div class='yarpp-related-rss'>
<h3>Related Posts</h3><ol>
<li><a href='http://viralpatel.net/blogs/parsing-reading-xml-file-in-java-xml-reading-java-tutorial/' rel='bookmark' title='Parsing / Reading XML file in Java.'>Parsing / Reading XML file in Java.</a></li>
<li><a href='http://viralpatel.net/blogs/20-useful-java-code-snippets-for-java-developers/' rel='bookmark' title='20 very useful Java code snippets for Java Developers'>20 very useful Java code snippets for Java Developers</a></li>
<li><a href='http://viralpatel.net/blogs/java-load-csv-file-to-database/' rel='bookmark' title='Java: How to Load CSV file into Database'>Java: How to Load CSV file into Database</a></li>
<li><a href='http://viralpatel.net/blogs/decompile-class-file-java-decompiler-class-java-class/' rel='bookmark' title='Decompile Java Class file using decompilers.'>Decompile Java Class file using decompilers.</a></li>
<li><a href='http://viralpatel.net/blogs/hibernate-one-to-one-mapping-tutorial-using-annotation/' rel='bookmark' title='Hibernate One To One Annotation Mapping Tutorial'>Hibernate One To One Annotation Mapping Tutorial</a></li>
<li><a href='http://viralpatel.net/blogs/java-read-write-excel-file-apache-poi/' rel='bookmark' title='Read / Write Excel file in Java using Apache POI'>Read / Write Excel file in Java using Apache POI</a></li>
<li><a href='http://viralpatel.net/blogs/hibernate-one-to-many-xml-mapping-tutorial/' rel='bookmark' title='Hibernate One To Many XML Mapping Tutorial'>Hibernate One To Many XML Mapping Tutorial</a></li>
</ol>
</div>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=1OHn3ztfXSc:-ldJIoJjMLE:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=1OHn3ztfXSc:-ldJIoJjMLE:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=1OHn3ztfXSc:-ldJIoJjMLE:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?i=1OHn3ztfXSc:-ldJIoJjMLE:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=1OHn3ztfXSc:-ldJIoJjMLE:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=1OHn3ztfXSc:-ldJIoJjMLE:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=I9og5sOYxJI" border="0"></img></a>
</div>]]></content:encoded>
			<wfw:commentRss>http://viralpatel.net/blogs/java-xml-xpath-tutorial-parse-xml/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://viralpatel.net/blogs/java-xml-xpath-tutorial-parse-xml/</feedburner:origLink></item>
		<item>
		<title>Android Internet Connection Status &amp; Network Change Receiver example</title>
		<link>http://feedproxy.google.com/~r/viralpatelnet/~3/DTsf7FAXCLw/</link>
		<comments>http://viralpatel.net/blogs/android-internet-connection-status-network-change/#comments</comments>
		<pubDate>Fri, 26 Apr 2013 08:17:54 +0000</pubDate>
		<dc:creator>Viral Patel</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[android emulator]]></category>

		<guid isPermaLink="false">http://viralpatel.net/blogs/?p=3026</guid>
		<description><![CDATA[If you are developing an Android app you may already fetching information from internet. While doing so there is a chance that internet connection is not available on users handset. Hence its always a good idea to check the network state before performing any task that requires internet connection. You might also want to check [...]<div class='yarpp-related-rss'>
<h3>Related Posts</h3><ol>
<li><a href='http://viralpatel.net/blogs/android-trigger-media-scanner-api/' rel='bookmark' title='Android: Trigger Media Scanner Programmatically'>Android: Trigger Media Scanner Programmatically</a></li>
<li><a href='http://viralpatel.net/blogs/android-install-uninstall-shortcut-example/' rel='bookmark' title='Android Install/Uninstall Shortcut example'>Android Install/Uninstall Shortcut example</a></li>
<li><a href='http://viralpatel.net/blogs/android-speech-to-text-api/' rel='bookmark' title='Android: Speech To Text using API'>Android: Speech To Text using API</a></li>
<li><a href='http://viralpatel.net/blogs/pick-image-from-galary-android-app/' rel='bookmark' title='How To Pick Image From Gallery in Android App'>How To Pick Image From Gallery in Android App</a></li>
<li><a href='http://viralpatel.net/blogs/android-preferences-activity-example/' rel='bookmark' title='Android Preferences Activity example'>Android Preferences Activity example</a></li>
<li><a href='http://viralpatel.net/blogs/database-connection-pooling-tomcat-eclipse-db/' rel='bookmark' title='Database Connection Pooling in Tomcat using Eclipse'>Database Connection Pooling in Tomcat using Eclipse</a></li>
<li><a href='http://viralpatel.net/blogs/enable-camera-in-android-emulator/' rel='bookmark' title='How To Enable Camera in Android Emulator'>How To Enable Camera in Android Emulator</a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>If you are developing an Android app you may already fetching information from internet. While doing so there is a chance that internet connection is not available on users handset. Hence its always a good idea to check the network state before performing any task that requires internet connection.</p>
<p>You might also want to check what kind of internet connection is available in handset. For example is wifi currently enabled? or is mobile data network is connected.</p>
<h2>Check Internet Connection</h2>
<p>Here is a simple code snippet that will help you identify what kind of internet connection a user has on her device. </p>
<p>First we need following permission in order to access network state. Add following permission to your AndroidManifest.xml file.</p>
<p>Permissions required to access network state:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;uses-permission android:name=&quot;android.permission.ACCESS_NETWORK_STATE&quot; /&gt;
</pre>
<p>Now check following utility class <code>NetworkUtil</code>. It has method <code>getConnectivityStatus</code> which returns an int constant depending on current network connection. If wifi is enabled, this method will return <code>TYPE_WIFI</code>. Similarly for mobile data network is returns <code>TYPE_MOBILE</code>. You got the idea!! </p>
<p>There is also method <code>getConnectivityStatusString</code> which returns current network state as a more readable string. </p>
<p><em>NetworkUtil.java</em></p>
<pre class="brush: java; title: ; notranslate">
package net.viralpatel.network;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class NetworkUtil {
	
	public static int TYPE_WIFI = 1;
	public static int TYPE_MOBILE = 2;
	public static int TYPE_NOT_CONNECTED = 0;
	
	
	public static int getConnectivityStatus(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
		if (null != activeNetwork) {
			if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
				return TYPE_WIFI;
			
			if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
				return TYPE_MOBILE;
		} 
		return TYPE_NOT_CONNECTED;
	}
	
	public static String getConnectivityStatusString(Context context) {
		int conn = NetworkUtil.getConnectivityStatus(context);
		String status = null;
		if (conn == NetworkUtil.TYPE_WIFI) {
			status = &quot;Wifi enabled&quot;;
		} else if (conn == NetworkUtil.TYPE_MOBILE) {
			status = &quot;Mobile data enabled&quot;;
		} else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
			status = &quot;Not connected to Internet&quot;;
		}
		return status;
	}
}
</pre>
<p>You can use this utility class in your android app to check the network state of the device at any moment. </p>
<p>Now this code will return you the current network state whenever the utility method is called. What if you want to do something in your android app when network state changes? Lets say when Wifi is disabled, you need to put your android app service to sleep so that it does not perform certain task. Now this is just one usecase. The idea is to create a hook which gets called whenever network state changes. And you can write your custom code in this hook to handle the change in network state.</p>
<h2>Broadcast Receiver to handle changes in Network state</h2>
<p>You can easily handle the changes in network state by creating your own Broadcast Receiver. Following is a broadcast receiver class where we handle the changes in network. </p>
<p>Check <code>onReceive()</code> method. This method will be called when state of network changes. Here we are just creating a Toast message and displaying current network state. You can write your custom code in here to handle changes in connection state.</p>
<p><em>NetworkChangeReceiver.java</em></p>
<pre class="brush: java; title: ; notranslate">
package net.viralpatel.network;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class NetworkChangeReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(final Context context, final Intent intent) {

		String status = NetworkUtil.getConnectivityStatusString(context);

		Toast.makeText(context, status, Toast.LENGTH_LONG).show();
	}
}
</pre>
<p>Once we define our BroadcastReceiver, we need to define the same in AndroidMenifest.xml file. Add following to your menifest file.</p>
<pre class="brush: xml; title: ; notranslate">
 &lt;application  ...&gt;
     ...
        &lt;receiver
            android:name=&quot;net.viralpatel.network.NetworkChangeReceiver&quot;
            android:label=&quot;NetworkChangeReceiver&quot; &gt;
            &lt;intent-filter&gt;
                &lt;action android:name=&quot;android.net.conn.CONNECTIVITY_CHANGE&quot; /&gt;
                &lt;action android:name=&quot;android.net.wifi.WIFI_STATE_CHANGED&quot; /&gt;
            &lt;/intent-filter&gt;
        &lt;/receiver&gt;
      ...
&lt;/application&gt;
</pre>
<p>We defined our broadcast receiver class in menifest file. Also we defined two intent <code>CONNECTIVITY_CHANGE</code> and <code>WIFI_STATE_CHANGED</code>. Thus this will register our receiver for given intents. Whenever there is change in network state, android will fire these intents and our broadcast receiver will be called.</p>
<p>Below is complete AndroidMenifest.xml file.</p>
<p><em>AndroidMenifest.xml</em></p>
<pre class="brush: xml; title: ; notranslate">
&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    package=&quot;net.viralpatel.network&quot;
    android:versionCode=&quot;1&quot;
    android:versionName=&quot;1.0&quot; &gt;

    &lt;uses-sdk
        android:minSdkVersion=&quot;8&quot;
        android:targetSdkVersion=&quot;15&quot; /&gt;

    &lt;uses-permission android:name=&quot;android.permission.ACCESS_NETWORK_STATE&quot; /&gt;

    &lt;application
        android:icon=&quot;@drawable/ic_launcher&quot;
        android:label=&quot;@string/app_name&quot;
        android:theme=&quot;@style/AppTheme&quot; &gt;
        &lt;receiver
            android:name=&quot;net.viralpatel.network.NetworkChangeReceiver&quot;
            android:label=&quot;NetworkChangeReceiver&quot; &gt;
            &lt;intent-filter&gt;
                &lt;action android:name=&quot;android.net.conn.CONNECTIVITY_CHANGE&quot; /&gt;
                &lt;action android:name=&quot;android.net.wifi.WIFI_STATE_CHANGED&quot; /&gt;
            &lt;/intent-filter&gt;
        &lt;/receiver&gt;
    &lt;/application&gt;

&lt;/manifest&gt;
</pre>
<p>Run this demo in android emulator  or actual device. </p>
<p>When Wifi is enabled, you&#8217;ll see a Toast message with message.<br />
<img src="http://img.viralpatel.net/2013/04/android-network-change-broadcast-wifi-enabled.png" alt="android-network-change-broadcast-wifi-enabled" width="270" height="450" class="aligncenter size-full wp-image-3028" /></p>
<p>Now disable Wifi. The toast message will show you message that internet connection is not available.<br />
<img src="http://img.viralpatel.net/2013/04/android-network-change-broadcast-receiver-not-connected.png" alt="android-network-change-broadcast-receiver-not-connected" width="270" height="450" class="aligncenter size-full wp-image-3027" /></p>
<p>Now enable mobile data network. The same will be show in toast message as soon as you enable mobile data connection.<br />
<img src="http://img.viralpatel.net/2013/04/android-data-connection-broadcast-receiver.png" alt="android-data-connection-broadcast-receiver" width="270" height="450" class="aligncenter size-full wp-image-3029" /></p>
<h2>Download Source Code</h2>
<p>Browse through the source code in following Git repository:<br />
<strong>GitHub:</strong> <a rel="nofollow" target="_new" href="https://github.com/viralpatel/android-network-change-detect-example">https://github.com/viralpatel/android-network-change-detect-example</a></p>
<p>Download complete source code:<br />
<strong>Download:</strong> <a href="https://viralpatel-net-tutorials.googlecode.com/files/android-network-change-detect-example.zip"><strong>android-network-change-detect-example.zip (376 KB)</strong></a></p>
<div class='yarpp-related-rss'>
<h3>Related Posts</h3><ol>
<li><a href='http://viralpatel.net/blogs/android-trigger-media-scanner-api/' rel='bookmark' title='Android: Trigger Media Scanner Programmatically'>Android: Trigger Media Scanner Programmatically</a></li>
<li><a href='http://viralpatel.net/blogs/android-install-uninstall-shortcut-example/' rel='bookmark' title='Android Install/Uninstall Shortcut example'>Android Install/Uninstall Shortcut example</a></li>
<li><a href='http://viralpatel.net/blogs/android-speech-to-text-api/' rel='bookmark' title='Android: Speech To Text using API'>Android: Speech To Text using API</a></li>
<li><a href='http://viralpatel.net/blogs/pick-image-from-galary-android-app/' rel='bookmark' title='How To Pick Image From Gallery in Android App'>How To Pick Image From Gallery in Android App</a></li>
<li><a href='http://viralpatel.net/blogs/android-preferences-activity-example/' rel='bookmark' title='Android Preferences Activity example'>Android Preferences Activity example</a></li>
<li><a href='http://viralpatel.net/blogs/database-connection-pooling-tomcat-eclipse-db/' rel='bookmark' title='Database Connection Pooling in Tomcat using Eclipse'>Database Connection Pooling in Tomcat using Eclipse</a></li>
<li><a href='http://viralpatel.net/blogs/enable-camera-in-android-emulator/' rel='bookmark' title='How To Enable Camera in Android Emulator'>How To Enable Camera in Android Emulator</a></li>
</ol>
</div>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=DTsf7FAXCLw:5LMAsS2DJZU:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=DTsf7FAXCLw:5LMAsS2DJZU:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=DTsf7FAXCLw:5LMAsS2DJZU:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?i=DTsf7FAXCLw:5LMAsS2DJZU:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=DTsf7FAXCLw:5LMAsS2DJZU:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=DTsf7FAXCLw:5LMAsS2DJZU:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=I9og5sOYxJI" border="0"></img></a>
</div>]]></content:encoded>
			<wfw:commentRss>http://viralpatel.net/blogs/android-internet-connection-status-network-change/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://viralpatel.net/blogs/android-internet-connection-status-network-change/</feedburner:origLink></item>
		<item>
		<title>Android: Activity name must be specified error</title>
		<link>http://feedproxy.google.com/~r/viralpatelnet/~3/TshLwsFTSMc/</link>
		<comments>http://viralpatel.net/blogs/activity-name-must-be-specified/#comments</comments>
		<pubDate>Thu, 27 Dec 2012 13:30:38 +0000</pubDate>
		<dc:creator>Viral Patel</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[android ADT SDK]]></category>
		<category><![CDATA[android development tools]]></category>

		<guid isPermaLink="false">http://viralpatel.net/blogs/?p=2998</guid>
		<description><![CDATA[If you are an avid Android developer there is a chance that you might have encountered this error. Activity name must be specified The error popups up when we create a new Android project in Eclipse. You have no idea how to solve this!! You try giving all the values but still the error doesn&#8217;t [...]<div class='yarpp-related-rss'>
<h3>Related Posts</h3><ol>
<li><a href='http://viralpatel.net/blogs/android-preferences-activity-example/' rel='bookmark' title='Android Preferences Activity example'>Android Preferences Activity example</a></li>
<li><a href='http://viralpatel.net/blogs/google-android-adt-sdk-and-eclipse-ide-integration-on-linux/' rel='bookmark' title='Google Android ADT, SDK and Eclipse IDE integration on Linux'>Google Android ADT, SDK and Eclipse IDE integration on Linux</a></li>
<li><a href='http://viralpatel.net/blogs/android-trigger-media-scanner-api/' rel='bookmark' title='Android: Trigger Media Scanner Programmatically'>Android: Trigger Media Scanner Programmatically</a></li>
<li><a href='http://viralpatel.net/blogs/android-taking-emulator-screen-shots-eclipse/' rel='bookmark' title='Android: Take Emulator Screen Shots in Eclipse'>Android: Take Emulator Screen Shots in Eclipse</a></li>
<li><a href='http://viralpatel.net/blogs/android-speech-to-text-api/' rel='bookmark' title='Android: Speech To Text using API'>Android: Speech To Text using API</a></li>
<li><a href='http://viralpatel.net/blogs/pick-image-from-galary-android-app/' rel='bookmark' title='How To Pick Image From Gallery in Android App'>How To Pick Image From Gallery in Android App</a></li>
<li><a href='http://viralpatel.net/blogs/enable-camera-in-android-emulator/' rel='bookmark' title='How To Enable Camera in Android Emulator'>How To Enable Camera in Android Emulator</a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>If you are an avid Android developer there is a chance that you might have encountered this error. </p>
<blockquote><p>Activity name must be specified
</p></blockquote>
<p><img src="http://img.viralpatel.net/2012/12/android-activity-name-must-be-specified-error.png" alt="android-activity-name-must-be-specified-error" width="452" height="452" class="aligncenter size-full wp-image-3002" /></p>
<p>The error popups up when we create a new Android project in Eclipse. </p>
<p>You have no idea how to solve this!! You try giving all the values but still the error doesn&#8217;t go away. </p>
<p>Here is a simple trick to resolve this problem. Basically the issue is with your Android Development Tools. You need to update that package. Follow below steps and you wont see <strong>Activity name must be specified</strong> error.</p>
<p><b>Step 1: Go to Windows &gt; Preferences</b><br />
<img src="http://img.viralpatel.net/2012/12/android-windows-preferences.png" alt="android-windows-preferences" width="421" height="426" class="aligncenter size-full wp-image-3001" /></p>
<p><b>Step 2: Under the preference menu, navigate to <em>Install/Update</em> and click <em>Uninstall or update</em> link</b><br />
<img src="http://img.viralpatel.net/2012/12/android-preference-insall-update.png" alt="android-preference-insall-update" width="534" height="431" class="aligncenter size-full wp-image-3000" /></p>
<p><b>Step 3: This shows installed plugins. Select <em>Android Development Tools</em> and press <em>Update&#8230;</em></b><br />
<img src="http://img.viralpatel.net/2012/12/android-development-tools-update.png" alt="android-development-tools-update" width="516" height="439" class="aligncenter size-full wp-image-2999" /></p>
<p>That should update the required plugins and you should good to go now. Try creating a new Android project in Eclipse. The error should vanish.</p>
<div class='yarpp-related-rss'>
<h3>Related Posts</h3><ol>
<li><a href='http://viralpatel.net/blogs/android-preferences-activity-example/' rel='bookmark' title='Android Preferences Activity example'>Android Preferences Activity example</a></li>
<li><a href='http://viralpatel.net/blogs/google-android-adt-sdk-and-eclipse-ide-integration-on-linux/' rel='bookmark' title='Google Android ADT, SDK and Eclipse IDE integration on Linux'>Google Android ADT, SDK and Eclipse IDE integration on Linux</a></li>
<li><a href='http://viralpatel.net/blogs/android-trigger-media-scanner-api/' rel='bookmark' title='Android: Trigger Media Scanner Programmatically'>Android: Trigger Media Scanner Programmatically</a></li>
<li><a href='http://viralpatel.net/blogs/android-taking-emulator-screen-shots-eclipse/' rel='bookmark' title='Android: Take Emulator Screen Shots in Eclipse'>Android: Take Emulator Screen Shots in Eclipse</a></li>
<li><a href='http://viralpatel.net/blogs/android-speech-to-text-api/' rel='bookmark' title='Android: Speech To Text using API'>Android: Speech To Text using API</a></li>
<li><a href='http://viralpatel.net/blogs/pick-image-from-galary-android-app/' rel='bookmark' title='How To Pick Image From Gallery in Android App'>How To Pick Image From Gallery in Android App</a></li>
<li><a href='http://viralpatel.net/blogs/enable-camera-in-android-emulator/' rel='bookmark' title='How To Enable Camera in Android Emulator'>How To Enable Camera in Android Emulator</a></li>
</ol>
</div>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=TshLwsFTSMc:pa-QwIF7TW0:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=TshLwsFTSMc:pa-QwIF7TW0:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=TshLwsFTSMc:pa-QwIF7TW0:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?i=TshLwsFTSMc:pa-QwIF7TW0:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=TshLwsFTSMc:pa-QwIF7TW0:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=TshLwsFTSMc:pa-QwIF7TW0:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=I9og5sOYxJI" border="0"></img></a>
</div>]]></content:encoded>
			<wfw:commentRss>http://viralpatel.net/blogs/activity-name-must-be-specified/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://viralpatel.net/blogs/activity-name-must-be-specified/</feedburner:origLink></item>
		<item>
		<title>Spring MVC Flash Attribute tutorial with example</title>
		<link>http://feedproxy.google.com/~r/viralpatelnet/~3/olnNXBCK9fs/</link>
		<comments>http://viralpatel.net/blogs/spring-mvc-flash-attribute-example/#comments</comments>
		<pubDate>Mon, 17 Dec 2012 13:58:16 +0000</pubDate>
		<dc:creator>Viral Patel</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[Spring 3 MVC]]></category>
		<category><![CDATA[spring mvc]]></category>

		<guid isPermaLink="false">http://viralpatel.net/blogs/?p=2987</guid>
		<description><![CDATA[Spring MVC 3.1 version has added a very useful feature Flash attribute which it lacked and is now solving a long time problem of POST/Redirect/GET pattern. In a normal Web based MVC application each form submitted POST the data to the server. A normal spring controller (tagged with annotation @Controller) fetches the data from request [...]<div class='yarpp-related-rss'>
<h3>Related Posts</h3><ol>
<li><a href='http://viralpatel.net/blogs/change-spring-servlet-filename-configuration/' rel='bookmark' title='Change spring-servlet.xml Filename (Spring Web Contenxt Configuration Filename)'>Change spring-servlet.xml Filename (Spring Web Contenxt Configuration Filename)</a></li>
<li><a href='http://viralpatel.net/blogs/spring-mvc-interceptor-example/' rel='bookmark' title='Spring 3 MVC Interceptor tutorial with example'>Spring 3 MVC Interceptor tutorial with example</a></li>
<li><a href='http://viralpatel.net/blogs/spring-3-mvc-handling-forms/' rel='bookmark' title='Spring 3 MVC: Handling Forms in Spring 3.0 MVC'>Spring 3 MVC: Handling Forms in Spring 3.0 MVC</a></li>
<li><a href='http://viralpatel.net/blogs/spring-3-mvc-internationalization-i18n-localization-tutorial-example/' rel='bookmark' title='Spring 3 MVC: Internationalization &amp; Localization Tutorial with Example'>Spring 3 MVC: Internationalization &#038; Localization Tutorial with Example</a></li>
<li><a href='http://viralpatel.net/blogs/errorsbindingresult-argument-declared-without-preceding-model-attribute/' rel='bookmark' title='Solve:Errors/BindingResult argument declared without preceding model attribute'>Solve:Errors/BindingResult argument declared without preceding model attribute</a></li>
<li><a href='http://viralpatel.net/blogs/spring-3-mvc-themes-tutorial-example/' rel='bookmark' title='Spring 3 MVC: Themes in Spring-Tutorial with Example'>Spring 3 MVC: Themes in Spring-Tutorial with Example</a></li>
<li><a href='http://viralpatel.net/blogs/tutorial-spring-3-mvc-introduction-spring-mvc-framework/' rel='bookmark' title='Spring 3 MVC – Introduction to Spring 3 MVC Framework'>Spring 3 MVC – Introduction to Spring 3 MVC Framework</a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>Spring MVC 3.1 version has added a very useful feature <em>Flash attribute</em> which it lacked and is now solving a long time problem of POST/Redirect/GET pattern. </p>
<p>In a normal Web based MVC application each form submitted POST the data to the server. A normal spring controller (tagged with annotation @Controller) fetches the data from request and process it further (save or update in database). Once the operation is successful, user is forwarded to page showing success of operation. Traditionally if we handle this via POST/Forward/GET, then it may cause sometime multiple form submission issue. User might press F5 and the same data is posted again.</p>
<p>To overcome this problem, <a rel="nofollow" href="http://en.wikipedia.org/wiki/Post/Redirect/Get">POST/Redirect/GET</a> pattern is used in MVC applcations. Once user form is posted successfully, we redirect the request to another success page. This causes browser to perform a new GET request and load the page. Thus is user presses F5, the GET request gets loaded instead of submitting form again.</p>
<p><img src="http://upload.wikimedia.org/wikipedia/commons/3/3c/PostRedirectGet_DoubleSubmitSolution.png" width="653" height="534" alt="POST/Redirect/GET" class="aligncenter" /><br />
<em>Image credit: Wikipedia</em></p>
<p>While this approach looks perfect and solve the problem of multiple form submission, it add one more issue of retrieving request parameters and attributes. Normally when we generate an http redirect request, the data stored in request is lost making it impossible for next GET request to access some of the useful information from request.</p>
<p>Flash attributes comes handy in such cases. Flash attributes provide a way for one request to store attributes intended for use in another. Flash attributes are saved temporarily (typically in the session) before the redirect to be made available to the request after the redirect and removed immediately.</p>
<p><img src="http://img.viralpatel.net/2012/12/spring-mvc-flash-map-manager.png" alt="spring-mvc-flash-map-manager" width="329" height="191" class="aligncenter size-full wp-image-2988" /></p>
<p>In order to do this, Flash feature uses two collections. <code>FlashMap</code> is used to hold flash attributes while <code>FlashMapManager</code> is used to store, retrieve, and manage <code>FlashMap</code> instances. </p>
<p>For each request an <strong>&#8220;input&#8221;</strong> flash map is created which stores flash attribute from any previous request and an <strong>&#8220;output&#8221;</strong> flash map is created which stores any subsequent attributes that we store in this request. </p>
<h2>Usage</h2>
<p>In order to use Flash attribute in your Spring MVC application make sure you using version <strong>3.1 or above</strong>. Also add <code>mvc:annotation-driven</code> to spring-servlet.xml file. </p>
<pre class="brush: xml; title: ; notranslate">
&lt;mvc:annotation-driven /&gt;
</pre>
<p>Once this is done, Flash attribute is automatically set &#8220;on&#8221; for usage. Just add attribute <code>RedirectAttributes redirectAttributes</code> to your Spring controller&#8217;s method.</p>
<pre class="brush: java; highlight: [6]; title: ; notranslate">
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
//...

	@RequestMapping(value=&quot;addcustomer&quot;, method=RequestMethod.POST)
	public String addCustomer(@ModelAttribute(&quot;customer&quot;) Customer customer,
			final RedirectAttributes redirectAttributes) {
	//...
		redirectAttributes.addFlashAttribute(&quot;message&quot;, &quot;Successfully added..&quot;);
	//...

		return &quot;redirect:some_other_request_name&quot;;
	}
</pre>
<p>The <code>addFlashAttribute</code> method automatically add the given parameter to the <strong>output</strong> flash map and pass it to the subsequent requests.</p>
<p>Let us see a complete demo application which uses Flash attribute to perform POST/Redirect/GET and passes some information.</p>
<h2>Flash Attribute Example</h2>
<p>The following application displays a form to user. Once the user inputs data and submits form, the page is redirected to another page where success message is displayed. On this new redirected page, the user input is displayed.</p>
<h2>Step 1: Required JAR and Project Structure</h2>
<p>If you using Maven as dependency management, use below dependencies to add Spring 3.1 MVC support. </p>
<pre class="brush: xml; title: ; notranslate">
	&lt;dependencies&gt;
		&lt;!-- Spring 3.1 MVC  --&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;org.springframework&lt;/groupId&gt;
			&lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt;
			&lt;version&gt;3.1.2.RELEASE&lt;/version&gt;
		&lt;/dependency&gt;
		&lt;!-- JSTL for c: tag --&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;jstl&lt;/groupId&gt;
			&lt;artifactId&gt;jstl&lt;/artifactId&gt;
			&lt;version&gt;1.2&lt;/version&gt;
		&lt;/dependency&gt;
	&lt;/dependencies&gt;
</pre>
<p>Alternatively, you can also download following JAR files and place them under <strong>/WEB-INF/lib</strong> folder.</p>
<p><img src="http://img.viralpatel.net/2012/12/spring-mvc-flash-attribute-jar-files.png" alt="spring-mvc-flash-attribute-jar-files" width="266" height="211" class="aligncenter size-full wp-image-2989" /></p>
<h2>Step 2: Spring Configuration</h2>
<p>Add Spring support to web project by adding DispatcherServlet to web.xml.<br />
web.xml</p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;web-app xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot; 
	xmlns:web=&quot;http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;
	xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee 

http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;

	id=&quot;WebApp_ID&quot; version=&quot;2.5&quot;&gt;
	
	&lt;display-name&gt;Spring MVC Flash attribute example&lt;/display-name&gt;
	&lt;servlet&gt;
		&lt;servlet-name&gt;spring&lt;/servlet-name&gt;
		&lt;servlet-class&gt;
			org.springframework.web.servlet.DispatcherServlet
		&lt;/servlet-class&gt;
		&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
	&lt;/servlet&gt;
	&lt;servlet-mapping&gt;
    	&lt;servlet-name&gt;default&lt;/servlet-name&gt;
    	&lt;url-pattern&gt;/index.html&lt;/url-pattern&gt;
	&lt;/servlet-mapping&gt;	
	&lt;servlet-mapping&gt;
		&lt;servlet-name&gt;spring&lt;/servlet-name&gt;
		&lt;url-pattern&gt;*.html&lt;/url-pattern&gt;
	&lt;/servlet-mapping&gt;
&lt;/web-app&gt;
</pre>
<p>Also the spring-servlet uses <code>mvc:annotation-driven</code> to enable mvc and also scans the project with <code>context:component-scan</code> tag.</p>
<p>spring-servlet.xml</p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml  version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
	xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
	xmlns:mvc=&quot;http://www.springframework.org/schema/mvc&quot;
	xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc  http://www.springframework.org/schema/mvc/spring-mvc.xsd&quot;&gt;
		
	
	&lt;bean id=&quot;jspViewResolver&quot;
	class=&quot;org.springframework.web.servlet.view.InternalResourceViewResolver&quot;&gt;
		&lt;property name=&quot;viewClass&quot;
			value=&quot;org.springframework.web.servlet.view.JstlView&quot; /&gt;
		&lt;property name=&quot;prefix&quot; value=&quot;/WEB-INF/jsp/&quot; /&gt;
		&lt;property name=&quot;suffix&quot; value=&quot;.jsp&quot; /&gt;
	 &lt;/bean&gt;
	
	&lt;context:component-scan base-package=&quot;net.viralpatel.controller&quot; /&gt;
	&lt;mvc:annotation-driven /&gt;
 
&lt;/beans&gt;
</pre>
<h2>Step 3: Spring Controller &#8211; RedirectAttributes</h2>
<p>The Controller code uses Customer.java object as bean (command) to holds customer information.</p>
<p>Customer.java</p>
<pre class="brush: java; title: ; notranslate">
package net.viralpatel.spring;

public class Customer {
	private String firstname;
	private String lastname;
	private int age;
	private String email;

	//getter, setter methods
}
</pre>
<p>The CustomerController class has 3 methods. Method <code>showForm</code> is mapped with <strong>/form</strong> URL and is used to display Add New Customer form. Th method <code>addCustomer</code> is mapped with URL <strong>/addcustomer</strong> and is used on POST request. </p>
<p>CustomerController.java</p>
<pre class="brush: java; title: ; notranslate">
package net.viralpatel.controller;

import net.viralpatel.spring.Customer;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class CustomerController {

	
	
	@RequestMapping(value=&quot;showform&quot;, method=RequestMethod.GET)
	public String showForm(@ModelAttribute(&quot;customer&quot;) Customer customer) {
		return &quot;add_customer&quot;;	
	}
	
	@RequestMapping(value=&quot;addcustomer&quot;, method=RequestMethod.POST)
	public String addCustomer(@ModelAttribute(&quot;customer&quot;) Customer customer,
			final RedirectAttributes redirectAttributes) {

		redirectAttributes.addFlashAttribute(&quot;customer&quot;, customer);
		redirectAttributes.addFlashAttribute(&quot;message&quot;,&quot;Added successfully.&quot;);

		return &quot;redirect:showcustomer.html&quot;;	
	}

	
	@RequestMapping(value=&quot;showcustomer&quot;, method=RequestMethod.GET)
	public String showCustomer(@ModelAttribute(&quot;customer&quot;) Customer customer) {
		System.out.println(&quot;cust:&quot; + customer.getFirstname());
		return &quot;show_customer&quot;;
	}
}

</pre>
<p>Note how we used <code>redirectAttributes</code> parameter on method <code>addCustomer</code> to map flash attributes. Also we used <code>addFlashAttribute</code> method to set new parameters to flash attribute.</p>
<h2>Step 4: Views</h2>
<p>The add customer JSP displays Add New Customer form.<br />
add_customer.jsp</p>
<pre class="brush: xml; title: ; notranslate">
&lt;%@taglib uri=&quot;http://www.springframework.org/tags/form&quot; prefix=&quot;form&quot;%&gt;
&lt;html&gt;
&lt;body&gt;
	&lt;h1&gt;Add New Customer&lt;/h1&gt;
	&lt;form:form action=&quot;addcustomer.html&quot; method=&quot;post&quot; commandName=&quot;customer&quot;&gt;
	&lt;table&gt;
		&lt;tr&gt;
			&lt;td&gt;&lt;form:label path=&quot;firstname&quot;&gt;Firstname&lt;/form:label&gt;&lt;/td&gt;
			&lt;td&gt;&lt;form:input path=&quot;firstname&quot; /&gt; &lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt;&lt;form:label path=&quot;lastname&quot;&gt;Lastname&lt;/form:label&gt;&lt;/td&gt;
			&lt;td&gt;&lt;form:input path=&quot;lastname&quot; /&gt; &lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt;&lt;form:label path=&quot;age&quot;&gt;Age&lt;/form:label&gt;&lt;/td&gt;
			&lt;td&gt;&lt;form:input path=&quot;age&quot; /&gt; &lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td&gt;&lt;form:label path=&quot;email&quot;&gt;Email&lt;/form:label&gt;
			&lt;td&gt;&lt;form:input path=&quot;email&quot; /&gt; &lt;/td&gt;
		&lt;/tr&gt;
		&lt;tr&gt;
			&lt;td colspan=&quot;2&quot;&gt;&lt;input type=&quot;submit&quot; value=&quot;Add Customer&quot; /&gt;
			&lt;/td&gt;
		&lt;/tr&gt;
	&lt;/table&gt;
	&lt;/form:form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Show customer JSP simply shows the customer&#8217;s first and last name and a success message set as flash attributes.</p>
<p>show_customer.jsp</p>
<pre class="brush: xml; title: ; notranslate">
&lt;%@taglib uri=&quot;http://www.springframework.org/tags/form&quot; prefix=&quot;form&quot;%&gt;
&lt;html&gt;
&lt;body&gt;
&lt;h1&gt;${message}&lt;/h1&gt;
	${customer.lastname}, ${customer.firstname} added successfully..
&lt;/body&gt;
&lt;/html&gt;
</pre>
<h2>Demo:</h2>
<p>Execute the web project.<br />
<strong>URL: http://localhost:8080/SpringMVC_Flash_Attribute_Maven_example/form.html</strong><br />
<img src="http://img.viralpatel.net/2012/12/spring-mvc-flash-attribute-demo-form.png" alt="spring-mvc-flash-attribute-demo-form" width="569" height="303" class="aligncenter size-full wp-image-2990" /></p>
<p><img src="http://img.viralpatel.net/2012/12/spring-mvc-flash-attribute-demo-success.png" alt="spring-mvc-flash-attribute-demo-success" width="630" height="212" class="aligncenter size-full wp-image-2991" /></p>
<h2>Download Source Code</h2>
<p><a href="http://viralpatel-net-tutorials.googlecode.com/files/SpringMVC_Flash_Attribute_Maven_example1.zip"><strong>SpringMVC_Flash_Attribute_example.zip (3.5 MB)</strong></a></p>
<div class='yarpp-related-rss'>
<h3>Related Posts</h3><ol>
<li><a href='http://viralpatel.net/blogs/change-spring-servlet-filename-configuration/' rel='bookmark' title='Change spring-servlet.xml Filename (Spring Web Contenxt Configuration Filename)'>Change spring-servlet.xml Filename (Spring Web Contenxt Configuration Filename)</a></li>
<li><a href='http://viralpatel.net/blogs/spring-mvc-interceptor-example/' rel='bookmark' title='Spring 3 MVC Interceptor tutorial with example'>Spring 3 MVC Interceptor tutorial with example</a></li>
<li><a href='http://viralpatel.net/blogs/spring-3-mvc-handling-forms/' rel='bookmark' title='Spring 3 MVC: Handling Forms in Spring 3.0 MVC'>Spring 3 MVC: Handling Forms in Spring 3.0 MVC</a></li>
<li><a href='http://viralpatel.net/blogs/spring-3-mvc-internationalization-i18n-localization-tutorial-example/' rel='bookmark' title='Spring 3 MVC: Internationalization &amp; Localization Tutorial with Example'>Spring 3 MVC: Internationalization &#038; Localization Tutorial with Example</a></li>
<li><a href='http://viralpatel.net/blogs/errorsbindingresult-argument-declared-without-preceding-model-attribute/' rel='bookmark' title='Solve:Errors/BindingResult argument declared without preceding model attribute'>Solve:Errors/BindingResult argument declared without preceding model attribute</a></li>
<li><a href='http://viralpatel.net/blogs/spring-3-mvc-themes-tutorial-example/' rel='bookmark' title='Spring 3 MVC: Themes in Spring-Tutorial with Example'>Spring 3 MVC: Themes in Spring-Tutorial with Example</a></li>
<li><a href='http://viralpatel.net/blogs/tutorial-spring-3-mvc-introduction-spring-mvc-framework/' rel='bookmark' title='Spring 3 MVC – Introduction to Spring 3 MVC Framework'>Spring 3 MVC – Introduction to Spring 3 MVC Framework</a></li>
</ol>
</div>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=olnNXBCK9fs:E-Y9jEWUAtg:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=olnNXBCK9fs:E-Y9jEWUAtg:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=olnNXBCK9fs:E-Y9jEWUAtg:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?i=olnNXBCK9fs:E-Y9jEWUAtg:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=olnNXBCK9fs:E-Y9jEWUAtg:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=olnNXBCK9fs:E-Y9jEWUAtg:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=I9og5sOYxJI" border="0"></img></a>
</div>]]></content:encoded>
			<wfw:commentRss>http://viralpatel.net/blogs/spring-mvc-flash-attribute-example/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		<feedburner:origLink>http://viralpatel.net/blogs/spring-mvc-flash-attribute-example/</feedburner:origLink></item>
		<item>
		<title>Dynamic Property Loader using Java Dynamic Proxy pattern</title>
		<link>http://feedproxy.google.com/~r/viralpatelnet/~3/7E26clsyZgo/</link>
		<comments>http://viralpatel.net/blogs/dynamic-property-loader-using-java-dynamic-proxy-pattern/#comments</comments>
		<pubDate>Thu, 13 Dec 2012 16:16:39 +0000</pubDate>
		<dc:creator>Viral Patel</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[java 5]]></category>
		<category><![CDATA[java reflection api]]></category>

		<guid isPermaLink="false">http://viralpatel.net/blogs/?p=2982</guid>
		<description><![CDATA[While reading through Stackoverflow, I came up to this interesting question: Java Properties File binding to Java Interface. The idea is simple but quite helpful. Basically we create an interface like: And whenever we want to use constant in our application, we simple use loginConstant.appDescription(). Our application framework creates a dynamic proxy implementation for this [...]<div class='yarpp-related-rss'>
<h3>Related Posts</h3><ol>
<li><a href='http://viralpatel.net/blogs/loading-java-properties-files/' rel='bookmark' title='Loading Java Properties Files'>Loading Java Properties Files</a></li>
<li><a href='http://viralpatel.net/blogs/static-import-java-example-tutorial/' rel='bookmark' title='Static Import in Java: New way to Import things in Java!'>Static Import in Java: New way to Import things in Java!</a></li>
<li><a href='http://viralpatel.net/blogs/java-dynamic-class-loading-java-reflection-api/' rel='bookmark' title='Dynamic Class Loading using Java Reflection API'>Dynamic Class Loading using Java Reflection API</a></li>
<li><a href='http://viralpatel.net/blogs/check-string-is-valid-date-java/' rel='bookmark' title='Check if String is valid Date in Java'>Check if String is valid Date in Java</a></li>
<li><a href='http://viralpatel.net/blogs/http-proxy-setting-java-setting-proxy-java/' rel='bookmark' title='HTTP Proxy setting in Java. Setting up proxy.'>HTTP Proxy setting in Java. Setting up proxy.</a></li>
<li><a href='http://viralpatel.net/blogs/java-singleton-design-pattern-tutorial-example-singleton-j2ee-design-pattern/' rel='bookmark' title='Java Singleton design pattern tutorial.'>Java Singleton design pattern tutorial.</a></li>
<li><a href='http://viralpatel.net/blogs/convert-string-to-enum-instance-string-enum-java/' rel='bookmark' title='Convert String to Enum Instance in Java'>Convert String to Enum Instance in Java</a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>While reading through Stackoverflow, I came up to this interesting question: <a href="http://stackoverflow.com/q/13861005/113418">Java Properties File binding to Java Interface</a>. The idea is simple but quite helpful.</p>
<p>Basically we create an interface like:</p>
<pre class="brush: java; title: ; notranslate">
interface LoginConstants extends Constants {
	   @DefaultStringValue(&quot;Welcome to my super app&quot;)
	   @Key(&quot;appDescription&quot;)
	   String appDescription();

	   @DefaultStringValue(&quot;Ok&quot;)
	   @Key(&quot;okButtonLabel&quot;)
	   String okButtonLabel();
} 
</pre>
<p>And whenever we want to use constant in our application, we simple use loginConstant.appDescription(). Our application framework creates a dynamic proxy implementation for this interface. All we have to do is just to call the method and we get the value either from property file or default one.</p>
<p>So below is the sample code:</p>
<p>So basically you create an interface with relevant methods and annotate them with @Key, @DefaultStringValue annotations.</p>
<p><strong>Disclaimer:</strong> This by no means should be used in Production. The code is just for reference. A lot more optimizations can be done in the below code. </p>
<p>Below is the sample Java code:</p>
<p>Main.java</p>
<pre class="brush: java; title: ; notranslate">
    package net.viralpatel;
    
    import net.viralpatel.annotations.DefaultStringValue;
    import net.viralpatel.annotations.Key;
    
    interface LoginConstants extends Constants {
    	   @DefaultStringValue(&quot;Wellcome to my super app&quot;)
    	   @Key(&quot;appDescription&quot;)
    	   String appDescription();
    
    	   @DefaultStringValue(&quot;Ok&quot;)
    	   @Key(&quot;okButtonLabel&quot;)
    	   String okButtonLabel();
    }
    
    public class Main {
    	public static void main(String[] args) {
    		LoginConstants constants = DynamicProperty.create(LoginConstants.class);
    		System.out.println(constants.appDescription());
    		System.out.println(constants.okButtonLabel());
    	}
    }
</pre>
<p>Also the property file in background that we load is</p>
<p>config.property</p>
<pre class="brush: plain; title: ; notranslate">
    okButtonLabel=This is OK
</pre>
<p>Just execute the Main java class, following output will be displayed:</p>
<p>Output:</p>
<pre class="brush: plain; title: ; notranslate">
    Wellcome to my super app 
    This is OK
</pre>
<p>So now the magic code. Well nothing is magical here. Just plain Java Dyna proxy using Reflection API</p>
<p>DefaultStringValue.java</p>
<pre class="brush: java; title: ; notranslate">
    package net.viralpatel.annotations;
    
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface DefaultStringValue {
    	public String value();
    }
</pre>
<p>Key.java</p>
<pre class="brush: java; title: ; notranslate">
    package net.viralpatel.annotations;
    
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface Key {
    	public String value();
    }
</pre>
<p>DynamicProperty.java</p>
<pre class="brush: java; title: ; notranslate">
    package net.viralpatel;
    
    import java.lang.reflect.Proxy;
    
    public class DynamicProperty {
    	
    	public static &lt;T extends Constants&gt; T  create(Class&lt;T&gt; clazz) {
    		
    		T object = (T) Proxy.newProxyInstance(clazz
    				.getClassLoader(), new Class[] { clazz },
    				new Handler(clazz));  
    		
    		return object;
    		
    	}
    }
</pre>
<p>Handler.java</p>
<pre class="brush: java; title: ; notranslate">
    package net.viralpatel;
    
    import java.lang.annotation.Annotation;
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    
    import net.viralpatel.annotations.DefaultStringValue;
    import net.viralpatel.annotations.Key;
    
    public class Handler implements InvocationHandler {
    	
    	Object obj;
    
    	public Handler(Object obj) {
    		this.obj = obj;
    	}
    	
    	public Object invoke(Object proxy, Method m, Object[] args)
    			throws Throwable {
    		String key = null;
    		String defaultValue = null;
    		try {
    
    			Annotation[] annotations = m.getAnnotations();
    			for (Annotation annotation : annotations) {
    				if (annotation instanceof Key) {
    					key = ((Key)annotation).value();
    				} else if (annotation instanceof DefaultStringValue) {
    					defaultValue = ((DefaultStringValue)annotation).value();
    				}
    			}
    
    			String ret = PropertyLoader.get(key);
    			return (null == ret) ? defaultValue : ret;
    			
    			// result = m.invoke(obj, args);
    
    		} catch (Exception e) {
    			// We could also put some code here if we want to do
    			// anything special in case an Exception is thrown from
    			// the inside of invoked method.
    			throw e;
    		}
    	}
    }
</pre>
<p>Constants.java</p>
<pre class="brush: java; title: ; notranslate">
    package net.viralpatel;
    
    public interface Constants {
    	//marker
    }
</pre>
<p>PropertyLoader.java</p>
<pre class="brush: java; title: ; notranslate">
    package net.viralpatel;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Properties;
    
    public class PropertyLoader {
    	private static Properties prop = null;
    
    	public static String get(String key) {
    		if (null == prop) {
    			init();
    		}
    		return (String) prop.get(key);
    	}
    
    	private static void init() {
    		prop = new Properties();
    		InputStream in = Properties.class
    				.getResourceAsStream(&quot;/net/viralpatel/config.properties&quot;);
    		try {
    			prop.load(in);
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    
    	}
    }
</pre>
<h2>Download Source Code</h2>
<p><a href="http://img.viralpatel.net/2012/12/Dynamic_Property_Java_Proxy.zip"><strong>Dynamic_Property_Java_Proxy.zip (12 KB)</strong></a><br />
<strong>Update</strong> Moved the code to Github for further development: <a rel="nofollow" target="_new" href="https://github.com/viralpatel/dynaproperty">github.com/viralpatel/dynaproperty</a></p>
<div class='yarpp-related-rss'>
<h3>Related Posts</h3><ol>
<li><a href='http://viralpatel.net/blogs/loading-java-properties-files/' rel='bookmark' title='Loading Java Properties Files'>Loading Java Properties Files</a></li>
<li><a href='http://viralpatel.net/blogs/static-import-java-example-tutorial/' rel='bookmark' title='Static Import in Java: New way to Import things in Java!'>Static Import in Java: New way to Import things in Java!</a></li>
<li><a href='http://viralpatel.net/blogs/java-dynamic-class-loading-java-reflection-api/' rel='bookmark' title='Dynamic Class Loading using Java Reflection API'>Dynamic Class Loading using Java Reflection API</a></li>
<li><a href='http://viralpatel.net/blogs/check-string-is-valid-date-java/' rel='bookmark' title='Check if String is valid Date in Java'>Check if String is valid Date in Java</a></li>
<li><a href='http://viralpatel.net/blogs/http-proxy-setting-java-setting-proxy-java/' rel='bookmark' title='HTTP Proxy setting in Java. Setting up proxy.'>HTTP Proxy setting in Java. Setting up proxy.</a></li>
<li><a href='http://viralpatel.net/blogs/java-singleton-design-pattern-tutorial-example-singleton-j2ee-design-pattern/' rel='bookmark' title='Java Singleton design pattern tutorial.'>Java Singleton design pattern tutorial.</a></li>
<li><a href='http://viralpatel.net/blogs/convert-string-to-enum-instance-string-enum-java/' rel='bookmark' title='Convert String to Enum Instance in Java'>Convert String to Enum Instance in Java</a></li>
</ol>
</div>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=7E26clsyZgo:P35KLeOp_l8:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=7E26clsyZgo:P35KLeOp_l8:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=7E26clsyZgo:P35KLeOp_l8:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?i=7E26clsyZgo:P35KLeOp_l8:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=7E26clsyZgo:P35KLeOp_l8:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=7E26clsyZgo:P35KLeOp_l8:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=I9og5sOYxJI" border="0"></img></a>
</div>]]></content:encoded>
			<wfw:commentRss>http://viralpatel.net/blogs/dynamic-property-loader-using-java-dynamic-proxy-pattern/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<feedburner:origLink>http://viralpatel.net/blogs/dynamic-property-loader-using-java-dynamic-proxy-pattern/</feedburner:origLink></item>
		<item>
		<title>Android Install/Uninstall Shortcut example</title>
		<link>http://feedproxy.google.com/~r/viralpatelnet/~3/hXwPw5gsqI8/</link>
		<comments>http://viralpatel.net/blogs/android-install-uninstall-shortcut-example/#comments</comments>
		<pubDate>Sun, 02 Dec 2012 10:47:59 +0000</pubDate>
		<dc:creator>Viral Patel</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[android-intent]]></category>

		<guid isPermaLink="false">http://viralpatel.net/blogs/?p=2972</guid>
		<description><![CDATA[Nowadays many android apps installs a shortcut on home screen when you install the app and run it for the first time. This is a nice strategy to engage user by compiling them to use your app. Most of times when a user install an app, the app is deep buried in list of apps [...]<div class='yarpp-related-rss'>
<h3>Related Posts</h3><ol>
<li><a href='http://viralpatel.net/blogs/android-trigger-media-scanner-api/' rel='bookmark' title='Android: Trigger Media Scanner Programmatically'>Android: Trigger Media Scanner Programmatically</a></li>
<li><a href='http://viralpatel.net/blogs/android-speech-to-text-api/' rel='bookmark' title='Android: Speech To Text using API'>Android: Speech To Text using API</a></li>
<li><a href='http://viralpatel.net/blogs/pick-image-from-galary-android-app/' rel='bookmark' title='How To Pick Image From Gallery in Android App'>How To Pick Image From Gallery in Android App</a></li>
<li><a href='http://viralpatel.net/blogs/android-preferences-activity-example/' rel='bookmark' title='Android Preferences Activity example'>Android Preferences Activity example</a></li>
<li><a href='http://viralpatel.net/blogs/android-taking-emulator-screen-shots-eclipse/' rel='bookmark' title='Android: Take Emulator Screen Shots in Eclipse'>Android: Take Emulator Screen Shots in Eclipse</a></li>
<li><a href='http://viralpatel.net/blogs/activity-name-must-be-specified/' rel='bookmark' title='Android: Activity name must be specified error'>Android: Activity name must be specified error</a></li>
<li><a href='http://viralpatel.net/blogs/android-internet-connection-status-network-change/' rel='bookmark' title='Android Internet Connection Status &amp; Network Change Receiver example'>Android Internet Connection Status &#038; Network Change Receiver example</a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>Nowadays many android apps installs a shortcut on home screen when you install the app and run it for the first time. This is a nice strategy to engage user by compiling them to use your app. Most of times when a user install an app, the app is deep buried in list of apps making it almost difficult to discover. So its always a good idea to make a shortcut right on home screen.</p>
<p>Android comes with simple yet undocumented API to add and remove shortcuts of any app on home screen. Let us check how to do this. </p>
<h2>1. Install Shortcut on Home screen</h2>
<p>Android provide us an intent class <code>com.android.launcher.action.INSTALL_SHORTCUT</code> which can be used to add shortcuts to home screen. In following code snippet we create a shortcut of activity <code>MainActivity</code> with the name HelloWorldShortcut.</p>
<p>First we need to add permission INSTALL_SHORTCUT to android manifest xml. </p>
<pre class="brush: xml; title: ; notranslate">
&lt;uses-permission 
        android:name=&quot;com.android.launcher.permission.INSTALL_SHORTCUT&quot; /&gt;
</pre>
<p>The addShortcut() method create a new shortcut on Home screen.</p>
<pre class="brush: java; title: ; notranslate">
    private void addShortcut() {
    	//Adding shortcut for MainActivity 
    	//on Home screen
		Intent shortcutIntent = new Intent(getApplicationContext(),
				MainActivity.class);
		
		shortcutIntent.setAction(Intent.ACTION_MAIN);

		Intent addIntent = new Intent();
		addIntent
				.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
		addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, &quot;HelloWorldShortcut&quot;);
		addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
				Intent.ShortcutIconResource.fromContext(getApplicationContext(),
						R.drawable.ic_launcher));

		addIntent
				.setAction(&quot;com.android.launcher.action.INSTALL_SHORTCUT&quot;);
		getApplicationContext().sendBroadcast(addIntent);
    }
</pre>
<p>Note how we create shortcutIntent object which holds our target activity. This intent object is added into another intent as EXTRA_SHORTCUT_INTENT. Finally we broadcast the new intent. This adds a shortcut with name mentioned as<br />
EXTRA_SHORTCUT_NAME and icon defined by EXTRA_SHORTCUT_ICON_RESOURCE. </p>
<p><strong>Note</strong>: One thing worth noting here is when you define your activity that is invoked from shortcut, you must define <strong>android:exported=&#8221;true&#8221;</strong> attribute in <code>&lt;activity&gt;</code> tag. You&#8217;ll see this in our demo. </p>
<h2>2. Uninstall Shortcut from Home screen</h2>
<p>Similar to install, uninstalling or removing shortcut in Android uses an Intent (UNINSTALL_SHORTCUT) to perform the task. In following code we remove the shortcut added on home screen.</p>
<p>Again we need a permission to perform uninstall shortcut task. Add following permission to Android manifest xml. </p>
<pre class="brush: xml; title: ; notranslate">
&lt;uses-permission 
        android:name=&quot;com.android.launcher.permission.UNINSTALL_SHORTCUT&quot; /&gt;
</pre>
<p>The <code>removeShortcut()</code> method does exactly reverse of addShortcut(). Most of the code is similar except removeShortcut calls <code>UNINSTALL_SHORTCUT</code> intent.</p>
<pre class="brush: java; title: ; notranslate">
    private void removeShortcut() {
    	
    	//Deleting shortcut for MainActivity 
    	//on Home screen
		Intent shortcutIntent = new Intent(getApplicationContext(),
				MainActivity.class);
		shortcutIntent.setAction(Intent.ACTION_MAIN);
		
		Intent addIntent = new Intent();
		addIntent
				.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
		addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, &quot;HelloWorldShortcut&quot;);

		addIntent
				.setAction(&quot;com.android.launcher.action.UNINSTALL_SHORTCUT&quot;);
		getApplicationContext().sendBroadcast(addIntent);
    }
</pre>
<p>Let us check the full functionality by creating a demo application.</p>
<h2>3. Demo Application</h2>
<p>The demo application is very simple. The user interface has two buttons: one to add shortcut to home screen and another to remove it.</p>
<p>Following is the simple layout consiting of two buttons.</p>
<p>layout/activity_main.xml</p>
<pre class="brush: xml; title: ; notranslate">
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot; 
    android:orientation=&quot;vertical&quot;&gt;
	    
    &lt;Button
        android:id=&quot;@+id/buttonAddShortcut&quot;
        android:layout_width=&quot;fill_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:text=&quot;Add Shortcut&quot; /&gt;

    &lt;Button
        android:id=&quot;@+id/buttonRemoveShortcut&quot;
        android:layout_width=&quot;fill_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:text=&quot;Remove Shortcut&quot; /&gt;
    
&lt;/LinearLayout&gt;
</pre>
<p>The layout looks something like following:<br />
<img src="http://img.viralpatel.net/2012/12/android_add_shortcut_demo.png" alt="android_add_shortcut_demo" title="android_add_shortcut_demo" width="264" height="440" class="aligncenter size-full wp-image-2978" /></p>
<p>The MainAcitivity is the activity class that handles user interface events. We add OnClickListener event handlers to both Add and Remove shortcut buttons. Each calls appropriate method to perform the task.</p>
<p>MainActivity.java</p>
<pre class="brush: java; title: ; notranslate">
package net.viralpatel.android;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.activity_main);
        
    	//Add listener to add shortcut button
    	Button add = (Button) findViewById(R.id.buttonAddShortcut);
    	add.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				addShortcut(); //Add shortcut on Home screen
			}
		});
    	
    	//Add listener to remove shortcut button
    	Button remove = (Button) findViewById(R.id.buttonRemoveShortcut);
    	remove.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				removeShortcut(); //Remove shortcut from Home screen
			}
		});    	
    }
    
    private void addShortcut() {
    	//Adding shortcut for MainActivity 
    	//on Home screen
		Intent shortcutIntent = new Intent(getApplicationContext(),
				MainActivity.class);
		
		shortcutIntent.setAction(Intent.ACTION_MAIN);

		Intent addIntent = new Intent();
		addIntent
				.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
		addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, &quot;HelloWorldShortcut&quot;);
		addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
			Intent.ShortcutIconResource.fromContext(getApplicationContext(),
						R.drawable.ic_launcher));

		addIntent
				.setAction(&quot;com.android.launcher.action.INSTALL_SHORTCUT&quot;);
		getApplicationContext().sendBroadcast(addIntent);
    }
    
    private void removeShortcut() {
    	
    	//Deleting shortcut for MainActivity 
    	//on Home screen
		Intent shortcutIntent = new Intent(getApplicationContext(),
				MainActivity.class);
		shortcutIntent.setAction(Intent.ACTION_MAIN);
		
		Intent addIntent = new Intent();
		addIntent
				.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
		addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, &quot;HelloWorldShortcut&quot;);

		addIntent
				.setAction(&quot;com.android.launcher.action.UNINSTALL_SHORTCUT&quot;);
		getApplicationContext().sendBroadcast(addIntent);
    }
    
}
</pre>
<p>Also following is the Android manifest file for reference.</p>
<p>AndroidManifest.xml</p>
<pre class="brush: xml; title: ; notranslate">
&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    package=&quot;net.viralpatel.android&quot;
    android:versionCode=&quot;1&quot;
    android:versionName=&quot;1.0&quot; &gt;

    &lt;uses-sdk
        android:minSdkVersion=&quot;8&quot;
        android:targetSdkVersion=&quot;15&quot; /&gt;
    
    &lt;uses-permission 
        android:name=&quot;com.android.launcher.permission.INSTALL_SHORTCUT&quot; /&gt;
    &lt;uses-permission 
        android:name=&quot;com.android.launcher.permission.UNINSTALL_SHORTCUT&quot; /&gt;
    
	&lt;application
        android:icon=&quot;@drawable/ic_launcher&quot;
        android:label=&quot;@string/app_name&quot;
        android:theme=&quot;@style/AppTheme&quot; &gt;
        &lt;activity
            android:name=&quot;.MainActivity&quot;
            android:label=&quot;@string/title_activity_main&quot; 
            android:exported=&quot;true&quot;&gt;
            &lt;intent-filter&gt;
                &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;

                &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
            &lt;/intent-filter&gt;
        &lt;/activity&gt;
   &lt;/application&gt;

&lt;/manifest&gt;
</pre>
<h2>Screenshots of App</h2>
<p>On clicking Add Shortcut button a toast message appears saying the shortcut has been successfully added on home screen.<br />
<img src="http://img.viralpatel.net/2012/12/android_install_shortcut_success.png" alt="android_install_shortcut_success" title="android_install_shortcut_success" width="252" height="416" class="aligncenter size-full wp-image-2976" /></p>
<p>If you check the home screen, you will find the shortcut present.<br />
<img src="http://img.viralpatel.net/2012/12/android_shortcut_home_screen.png" alt="android_shortcut_home_screen" title="android_shortcut_home_screen" width="240" height="400" class="aligncenter size-full wp-image-2977" /></p>
<p>The remove shortcut button triggers UNINSTALL_SHORTCUT intent and removes the shortcut from home screen. It also prints a toast message with confirmation.<br />
<img src="http://img.viralpatel.net/2012/12/android_unistall_shortcut_demo.png" alt="android_unistall_shortcut_demo" title="android_unistall_shortcut_demo" width="253" height="417" class="aligncenter size-full wp-image-2975" /></p>
<h2>Download Source Code</h2>
<p><a href="http://viralpatel-net-tutorials.googlecode.com/files/Android_Add_Shortcut_example.zip" title="Android_Add_Shortcut_example.zip (689 KB)"><b>Android_Add_Shortcut_example.zip (689 KB)</b></a></p>
<div class='yarpp-related-rss'>
<h3>Related Posts</h3><ol>
<li><a href='http://viralpatel.net/blogs/android-trigger-media-scanner-api/' rel='bookmark' title='Android: Trigger Media Scanner Programmatically'>Android: Trigger Media Scanner Programmatically</a></li>
<li><a href='http://viralpatel.net/blogs/android-speech-to-text-api/' rel='bookmark' title='Android: Speech To Text using API'>Android: Speech To Text using API</a></li>
<li><a href='http://viralpatel.net/blogs/pick-image-from-galary-android-app/' rel='bookmark' title='How To Pick Image From Gallery in Android App'>How To Pick Image From Gallery in Android App</a></li>
<li><a href='http://viralpatel.net/blogs/android-preferences-activity-example/' rel='bookmark' title='Android Preferences Activity example'>Android Preferences Activity example</a></li>
<li><a href='http://viralpatel.net/blogs/android-taking-emulator-screen-shots-eclipse/' rel='bookmark' title='Android: Take Emulator Screen Shots in Eclipse'>Android: Take Emulator Screen Shots in Eclipse</a></li>
<li><a href='http://viralpatel.net/blogs/activity-name-must-be-specified/' rel='bookmark' title='Android: Activity name must be specified error'>Android: Activity name must be specified error</a></li>
<li><a href='http://viralpatel.net/blogs/android-internet-connection-status-network-change/' rel='bookmark' title='Android Internet Connection Status &amp; Network Change Receiver example'>Android Internet Connection Status &#038; Network Change Receiver example</a></li>
</ol>
</div>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=hXwPw5gsqI8:NDA__En-nQM:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=hXwPw5gsqI8:NDA__En-nQM:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=hXwPw5gsqI8:NDA__En-nQM:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?i=hXwPw5gsqI8:NDA__En-nQM:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=hXwPw5gsqI8:NDA__En-nQM:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=hXwPw5gsqI8:NDA__En-nQM:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=I9og5sOYxJI" border="0"></img></a>
</div>]]></content:encoded>
			<wfw:commentRss>http://viralpatel.net/blogs/android-install-uninstall-shortcut-example/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<feedburner:origLink>http://viralpatel.net/blogs/android-install-uninstall-shortcut-example/</feedburner:origLink></item>
		<item>
		<title>Struts 2 Action Chaining example</title>
		<link>http://feedproxy.google.com/~r/viralpatelnet/~3/smIbLH2FdYs/</link>
		<comments>http://viralpatel.net/blogs/struts-2-action-chaining-example/#comments</comments>
		<pubDate>Fri, 30 Nov 2012 15:37:54 +0000</pubDate>
		<dc:creator>Viral Patel</dc:creator>
				<category><![CDATA[Struts 2]]></category>
		<category><![CDATA[Struts2]]></category>
		<category><![CDATA[struts2-series]]></category>

		<guid isPermaLink="false">http://viralpatel.net/blogs/?p=2971</guid>
		<description><![CDATA[In Struts 2, sometimes you may want to process another action when one action completes. For example on successfully submitting a form you want to render output from other action. This is called Action chaining in Struts 2. One action leads to another one and so on. Request &#62; Action 1 &#62; Action 2 &#62; [...]<div class='yarpp-related-rss'>
<h3>Related Posts</h3><ol>
<li><a href='http://viralpatel.net/blogs/struts-2-tiles-plugin-tutorial-with-example-in-eclipse/' rel='bookmark' title='Struts 2 Tiles Plugin Tutorial with Example in Eclipse'>Struts 2 Tiles Plugin Tutorial with Example in Eclipse</a></li>
<li><a href='http://viralpatel.net/blogs/struts2-interceptors-tutorial-with-example/' rel='bookmark' title='Struts2 Interceptors Tutorial with Example'>Struts2 Interceptors Tutorial with Example</a></li>
<li><a href='http://viralpatel.net/blogs/struts-2-file-upload-save-tutorial-with-example/' rel='bookmark' title='Struts 2 File Upload and Save Tutorial with Example'>Struts 2 File Upload and Save Tutorial with Example</a></li>
<li><a href='http://viralpatel.net/blogs/introduction-to-struts-2-framework/' rel='bookmark' title='Introduction to Struts 2 Framework'>Introduction to Struts 2 Framework</a></li>
<li><a href='http://viralpatel.net/blogs/tutorial-struts-spring-framework-example-in-eclipse/' rel='bookmark' title='Tutorial:Struts Spring framework example in Eclipse.'>Tutorial:Struts Spring framework example in Eclipse.</a></li>
<li><a href='http://viralpatel.net/blogs/tutorial-create-struts-2-application-eclipse-example/' rel='bookmark' title='Tutorial: Create Struts 2 Application in Eclipse'>Tutorial: Create Struts 2 Application in Eclipse</a></li>
<li><a href='http://viralpatel.net/blogs/struts-2-ajax-tutorial-example-drop-down/' rel='bookmark' title='Struts 2 Ajax Tutorial with Example'>Struts 2 Ajax Tutorial with Example</a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/apache-struts-logo.jpg" alt="apache-struts-logo" title="apache-struts-logo" width="197" height="119" class="alignleft size-full wp-image-951" />In Struts 2, sometimes you may want to process another action when one action completes. For example on successfully submitting a form you want to render output from other action.</p>
<p>This is called Action chaining in Struts 2. One action leads to another one and so on. </p>
<p><b>Request &gt; Action 1 &gt; Action 2 &gt; Response</b></p>
<p>In Struts 2, this can be achieved by Chain Result. The Chain Result is a result type that invokes an Action with its own <a href="http://viralpatel.net/blogs/struts2-interceptors-tutorial-with-example/" rel="nofollow">Interceptor</a> Stack and Result. This Interceptor allows an Action to forward requests to a target Action, while propagating the state of the source Action. Below is an example of how to define this sequence.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;package name=&quot;public&quot; extends=&quot;struts-default&quot;&gt;
        &lt;action name=&quot;createUserAccount&quot;
            class=&quot;net.viralpatel.CreateAccountAction&quot;&gt;
            &lt;result name=&quot;success&quot; type=&quot;chain&quot;&gt;login&lt;/result&gt;
        &lt;/action&gt;
        &lt;action name=&quot;login&quot;
            class=&quot;net.viralpatel.LoginAction&quot;&gt;
            &lt;result name=&quot;success&quot; type=&quot;chain&quot;&gt;showDashboard&lt;/result&gt;
        &lt;/action&gt;
        &lt;action name=&quot;showDashboard&quot;
            class=&quot;net.viralpatel.DashboardAction&quot;&gt;
            &lt;result name=&quot;success&quot;&gt;/WEB-INF/jsp/dashboard.jsp&lt;/result&gt;
        &lt;/action&gt;
&lt;/package&gt;
</pre>
<p>In above code we define three actions: createUserAccount, login and showDashboard. Notice how each action is chained to the next one using <code>&lt;result type="chain"&gt;</code> tag. Thus when user logs in first time in system, the createAccount action will be used. Once account is created user is forwarded to login action. </p>
<h2>Disadvantage of Action Chaining</h2>
<p>The Action chaining must be used with precaution. Struts2 documentation too doesn&#8217;t support this feature. </p>
<p>Experience shows that chaining should be used with care. If chaining is overused, an application can turn into &#8220;spaghetti code&#8221;. Actions should be treated as a Transaction Script, rather than as methods in a Business Facade. Be sure to ask yourself why you need to chain from one Action to another. Is a navigational issue, or could the logic in Action2 be pushed back to a support class or business facade so that Action1 can call it too?</p>
<h2>Alternative: Redirect After Post</h2>
<p>You can use Redirect After Post mechanism in cases where you cannot avoid chaining other actions. This is more or less similar to Action chaining with a major difference. The response is told to redirect the browser to the specified location (a new request from the client). The consequence of doing this means that the action (action instance, action errors, field errors, etc) that was just executed is lost and no longer available. This is because actions are built on a single-thread model. The only way to pass data is through the session or with web parameters (url?name=value) which can be OGNL expressions.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;result name=&quot;success&quot; type=&quot;redirect&quot;&gt;
  &lt;param name=&quot;location&quot;&gt;foo.jsp&lt;/param&gt;
  &lt;param name=&quot;parse&quot;&gt;false&lt;/param&gt;
&lt;/result&gt;
</pre>
<p>In above result mapping we defined attribute type as <b>redirect</b>. Also notice how we defined two parameters location and parse.</p>
<ul>
<li><code>location</code> (default) &#8211; the location to go to after execution.</li>
<li><code>parse</code> &#8211; true by default. If set to false, the location param will not be parsed for Ognl expressions.</li>
</ul>
<p>The above example of action chaining (create account > login > dashboard) can be implemented using Redirect as follows:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;action name=&quot;createUserAccount&quot;
	class=&quot;net.viralpatel.CreateAccountAction&quot;&gt;
	&lt;result name=&quot;success&quot; type=&quot;redirect&quot;&gt;login&lt;/result&gt;
&lt;/action&gt;
&lt;action name=&quot;login&quot;
	class=&quot;net.viralpatel.LoginAction&quot;&gt;
	&lt;result name=&quot;success&quot; type=&quot;redirect&quot;&gt;showDashboard&lt;/result&gt;
&lt;/action&gt;
&lt;action name=&quot;showDashboard&quot;
	class=&quot;net.viralpatel.DashboardAction&quot;&gt;
	&lt;result name=&quot;success&quot;&gt;/WEB-INF/jsp/dashboard.jsp&lt;/result&gt;
&lt;/action&gt;
</pre>
<div class='yarpp-related-rss'>
<h3>Related Posts</h3><ol>
<li><a href='http://viralpatel.net/blogs/struts-2-tiles-plugin-tutorial-with-example-in-eclipse/' rel='bookmark' title='Struts 2 Tiles Plugin Tutorial with Example in Eclipse'>Struts 2 Tiles Plugin Tutorial with Example in Eclipse</a></li>
<li><a href='http://viralpatel.net/blogs/struts2-interceptors-tutorial-with-example/' rel='bookmark' title='Struts2 Interceptors Tutorial with Example'>Struts2 Interceptors Tutorial with Example</a></li>
<li><a href='http://viralpatel.net/blogs/struts-2-file-upload-save-tutorial-with-example/' rel='bookmark' title='Struts 2 File Upload and Save Tutorial with Example'>Struts 2 File Upload and Save Tutorial with Example</a></li>
<li><a href='http://viralpatel.net/blogs/introduction-to-struts-2-framework/' rel='bookmark' title='Introduction to Struts 2 Framework'>Introduction to Struts 2 Framework</a></li>
<li><a href='http://viralpatel.net/blogs/tutorial-struts-spring-framework-example-in-eclipse/' rel='bookmark' title='Tutorial:Struts Spring framework example in Eclipse.'>Tutorial:Struts Spring framework example in Eclipse.</a></li>
<li><a href='http://viralpatel.net/blogs/tutorial-create-struts-2-application-eclipse-example/' rel='bookmark' title='Tutorial: Create Struts 2 Application in Eclipse'>Tutorial: Create Struts 2 Application in Eclipse</a></li>
<li><a href='http://viralpatel.net/blogs/struts-2-ajax-tutorial-example-drop-down/' rel='bookmark' title='Struts 2 Ajax Tutorial with Example'>Struts 2 Ajax Tutorial with Example</a></li>
</ol>
</div>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=smIbLH2FdYs:aVnzhXz68bo:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=smIbLH2FdYs:aVnzhXz68bo:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=smIbLH2FdYs:aVnzhXz68bo:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?i=smIbLH2FdYs:aVnzhXz68bo:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=smIbLH2FdYs:aVnzhXz68bo:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=smIbLH2FdYs:aVnzhXz68bo:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=I9og5sOYxJI" border="0"></img></a>
</div>]]></content:encoded>
			<wfw:commentRss>http://viralpatel.net/blogs/struts-2-action-chaining-example/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://viralpatel.net/blogs/struts-2-action-chaining-example/</feedburner:origLink></item>
	</channel>
</rss><!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk
Page Caching using memcached
Database Caching 11/98 queries in 0.055 seconds using memcached
Object Caching 2697/2731 objects using memcached

 Served from: viralpatel.net @ 2013-05-24 00:56:11 by W3 Total Cache -->
