<?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>Tue, 15 May 2012 13:08:23 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.3.2</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>Deleting Multiple Values From Listbox in JavaScript</title><link>http://feedproxy.google.com/~r/viralpatelnet/~3/uI_otG12Krg/javascript-delete-multiple-values-options-listbox.html</link> <comments>http://viralpatel.net/blogs/2012/05/javascript-delete-multiple-values-options-listbox.html#comments</comments> <pubDate>Tue, 15 May 2012 13:08:23 +0000</pubDate> <dc:creator>Mukesh Gupta</dc:creator> <category><![CDATA[JavaScript]]></category> <category><![CDATA[dynamic combobox]]></category> <category><![CDATA[listbox]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2767</guid> <description><![CDATA[There was a requirement of deleting multiple options from a listbox using JavaScript. User can select multiple items from a Listbox. Once the delete button is pressed, remove all the values that are selected from the combobox. Now the most intuitive solution for this problem would be to iterate through each option from the listbox [...]]]></description> <content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/lsS2bxZx97q5XNVLe37N6EVN98A/0/da"><img src="http://feedads.g.doubleclick.net/~a/lsS2bxZx97q5XNVLe37N6EVN98A/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/lsS2bxZx97q5XNVLe37N6EVN98A/1/da"><img src="http://feedads.g.doubleclick.net/~a/lsS2bxZx97q5XNVLe37N6EVN98A/1/di" border="0" ismap="true"></img></a></p><p><img src="http://img.viralpatel.net/2012/05/remove-items-listbox.jpg" alt="remove-items-listbox" title="remove-items-listbox" width="188" height="240" class="alignright size-full wp-image-2768" />There was a requirement of deleting multiple options from a listbox using JavaScript. User can select multiple items from a Listbox. Once the delete button is pressed, remove all the values that are selected from the combobox.</p><p>Now the most intuitive solution for this problem would be to iterate through each option from the listbox and delete it if it is selected. So one would write following piece of HTML &#038; JavaScript.</p><h2>The HTML</h2><p>Define a simple listbox with id <strong>lsbox</strong> and two buttons, <strong>Delete</strong> &#038; <strong>Reset</strong>.</p><pre class="brush: xml; title: ; notranslate">
&lt;table&gt;
&lt;tr&gt;
	&lt;td align=&quot;center&quot;&gt;
		&lt;select id=&quot;lsbox&quot; name=&quot;lsbox&quot; size=&quot;10&quot; multiple&gt;
			&lt;option value=&quot;1&quot;&gt;India&lt;/option&gt;
			&lt;option value=&quot;2&quot;&gt;United States&lt;/option&gt;
			&lt;option value=&quot;3&quot;&gt;China&lt;/option&gt;
			&lt;option value=&quot;4&quot;&gt;Italy&lt;/option&gt;
			&lt;option value=&quot;5&quot;&gt;Germany&lt;/option&gt;
			&lt;option value=&quot;6&quot;&gt;Canada&lt;/option&gt;
			&lt;option value=&quot;7&quot;&gt;France&lt;/option&gt;
			&lt;option value=&quot;8&quot;&gt;United Kingdom&lt;/option&gt;
		&lt;/select&gt;
	&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
	&lt;td align=&quot;center&quot;&gt;
		&lt;button onclick=&quot;listbox_remove('lsbox');&quot;&gt;Delete&lt;/button&gt;
		&lt;button onclick=&quot;window.location.reload();&quot;&gt;Reset&lt;/button&gt;
	&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
</pre><p>Below is the JavaScript code.</p><h2>The (Incorrect) JavaScript</h2><pre class="brush: jscript; title: ; notranslate">
function listbox_remove(sourceID) {

    //get the listbox object from id.
    var src = document.getElementById(sourceID);

    //iterate through each option of the listbox
    for(var count = 0; count &lt; src.options.length; count--) {
         //if the option is selected, delete the option
        if(src.options[count].selected == true) {
                var option = src.options[count];

                try {
                         src.remove(count, null);

                 } catch(error) {

                         src.remove(count);
                }
        }
    }
}
</pre><p>That&#8217;s it right? Wait, this wont work correctly. Each time you delete an option using <code>src.remove()</code> method, the remaining option&#8217;s index will decrease by 1. So if you have selected multiple values to delete, this wont behave as you expected.</p><p>Check out the below demo:</p><h2>Demo: The Incorrect Way</h2><p>In following demo, we used the normal approach (above javascript) to remove the options.<br /> <iframe src="http://viralpatel.net/blogs/demo/js/delete-multiple-values-listbox/delete-multiple-values-listbox-incorrect.html" width="100%" height="300px" ></iframe></p><p>So we know the problem now. Each time the value is deleted, the index of option is decremented. So the ideal approach must be to iterate through the options of listbox in opposite way. Thus we start with the last options and iterate till first.</p><h2>The Correct JavaScript</h2><p>Notice the loop at line: XX. We are iterating in opposite direction.</p><pre class="brush: jscript; highlight: [7]; title: ; notranslate">
function listbox_remove(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) {
                var option = src.options[count];

                try {
                         src.remove(count, null);

                 } catch(error) {

                         src.remove(count);
                }
        }
    }
}
</pre><p>Following is the demo with correct JavaScript.</p><h2>Demo: The Correct Way</h2><p>In following demo, we used the correct approach (javascript) to remove the values.<br /> <iframe src="http://viralpatel.net/blogs/demo/js/delete-multiple-values-listbox/delete-multiple-values-listbox.html" width="100%" height="300px"></iframe></p><p>Hope this helps!</p><h2>Download Source Code</h2><p><a href="http://viralpatel.net/blogs/demo/js/delete-multiple-values-listbox/Delete_Multiple_Values_Listbox.zip"><strong>Delete_Multiple_Values_Listbox.zip (1.2 KB)</strong></a></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/06/listbox-select-all-move-left-right-up-down-javascript.html" 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/2009/03/javascript-multiple-selection-listbox-problem-ms-internet-explorer.html" title="Multiple Selection Listbox Javascript Problem in MS Internet Explorer">Multiple Selection Listbox Javascript Problem in MS Internet Explorer</a></li><li><a href="http://viralpatel.net/blogs/2009/01/dynamic-add-textbox-input-button-radio-element-html-javascript.html" 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/2008/12/dynamic-combobox-listbox-drop-down-using-javascript.html" title="Dynamic combobox-listbox-drop-down using javascript">Dynamic combobox-listbox-drop-down using javascript</a></li><li><a href="http://viralpatel.net/blogs/2012/01/stopsopa-jquery-plugin.html" title="STOP SOPA JQuery Plugin">STOP SOPA JQuery Plugin</a></li><li><a href="http://viralpatel.net/blogs/2012/01/create-zip-file-javascript.html" title="Create ZIP Files in JavaScript">Create ZIP Files in JavaScript</a></li><li><a href="http://viralpatel.net/blogs/2010/11/multiple-checkbox-select-deselect-jquery-tutorial-example.html" title="Multiple Checkbox Select/Deselect using jQuery &#8211; Tutorial with Example">Multiple Checkbox Select/Deselect using jQuery &#8211; Tutorial with Example</a></li></ul></div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=uI_otG12Krg:rITvjlu1Pn8:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=uI_otG12Krg:rITvjlu1Pn8:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=uI_otG12Krg:rITvjlu1Pn8:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?i=uI_otG12Krg:rITvjlu1Pn8:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=uI_otG12Krg:rITvjlu1Pn8:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=uI_otG12Krg:rITvjlu1Pn8:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=I9og5sOYxJI" border="0"></img></a>
</div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2012/05/javascript-delete-multiple-values-options-listbox.html/feed</wfw:commentRss> <slash:comments>0</slash:comments> <feedburner:origLink>http://viralpatel.net/blogs/2012/05/javascript-delete-multiple-values-options-listbox.html</feedburner:origLink></item> <item><title>org.hibernate.AnnotationException: No identifier specified for entity</title><link>http://feedproxy.google.com/~r/viralpatelnet/~3/E_nyG570x70/org-hibernate-annotationexception-no-identifier-specified.html</link> <comments>http://viralpatel.net/blogs/2012/05/org-hibernate-annotationexception-no-identifier-specified.html#comments</comments> <pubDate>Thu, 10 May 2012 11:53:00 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Hibernate]]></category> <category><![CDATA[annotation]]></category> <category><![CDATA[hibernate-orm]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2764</guid> <description><![CDATA[When you are writing a piece of code from scratch a lot of time you do silly mistakes and still wonder why its not working. Well same thing happened the other day when I added a Hibernate Entity class in one project and was struggling to make it work. The exception was: The error here [...]]]></description> <content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/Vhe9Oty3CGaFczbZvNpTuX11Sew/0/da"><img src="http://feedads.g.doubleclick.net/~a/Vhe9Oty3CGaFczbZvNpTuX11Sew/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/Vhe9Oty3CGaFczbZvNpTuX11Sew/1/da"><img src="http://feedads.g.doubleclick.net/~a/Vhe9Oty3CGaFczbZvNpTuX11Sew/1/di" border="0" ismap="true"></img></a></p><p>When you are writing a piece of code from scratch a lot of time you do silly mistakes and still wonder why its not working. Well same thing happened the other day when I added a Hibernate Entity class in one project and was struggling to make it work.</p><p>The exception was:</p><pre class="brush: java; title: ; notranslate">

org.hibernate.AnnotationException: No identifier specified for entity: net.viralpatel.hibernate.Employee
	at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:650)
	at org.hibernate.cfg.AnnotationConfiguration.processArtifactsOfType(AnnotationConfiguration.java:498)
	at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:277)
	at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1112)
	at org.hibernate.ejb.Ejb3Configuration.buildMappings(Ejb3Configuration.java:1269)
	at org.hibernate.ejb.EventListenerConfigurator.configure(EventListenerConfigurator.java:150)
	at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:888)
	at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:416)
	at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:126)
	at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:227)
	at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:273)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1367)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1333)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:471)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
	at java.security.AccessController.doPrivileged(Native Method)
</pre><p>The error here is that in your Entity class, you have not defined a primary key. Thus specify either <code>@Id</code> annotation or an <code>@EmbeddedId</code> annotation.</p><p>So if you have an entity class Employee like below:</p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name=&quot;EMPLOYEE&quot;)
public class Employee {

    @Column(name=&quot;employee_id&quot;)
    private Long employeeId;

    @Column(name=&quot;firstname&quot;)
    private String firstname;

    @Column(name=&quot;lastname&quot;)
    private String lastname;

    //Getter and Setter methods	

}</pre><p>And if you try to execute this, it will generate exception <strong>org.hibernate.AnnotationException: No identifier specified for entity: net.viralpatel.hibernate.Employee</strong></p><p>So the solution is just add @Id to appropriate primary key column.</p><pre class="brush: java; highlight: [12]; title: ; notranslate">
package net.viralpatel.hibernate;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Id;

@Entity
@Table(name=&quot;EMPLOYEE&quot;)
public class Employee {

    @Id
    @Column(name=&quot;employee_id&quot;)
    private Long employeeId;

    @Column(name=&quot;firstname&quot;)
    private String firstname;

    @Column(name=&quot;lastname&quot;)
    private String lastname;

    //Getter and Setter methods	

}</pre><p>Thus every class defined as Entity with @Entity annotation, needs an @Id or @EmbeddedId property.</p><p>Hope that helps and reduce your debugging effort.</p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotation-mapping-many-to-many-example.html" title="Hibernate Self Join Many To Many Annotations mapping example">Hibernate Self Join Many To Many Annotations mapping example</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-annotation-tutorial.html" title="Hibernate One To Many Annotation tutorial">Hibernate One To Many Annotation tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-hello-world-example-annotation.html" title="Hibernate Hello World example using Annotation">Hibernate Hello World example using Annotation</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-concrete-class-annotation-xml-mapping.html" title="Hibernate Inheritance: Table Per Concrete Class (Annotation &#038; XML mapping)">Hibernate Inheritance: Table Per Concrete Class (Annotation &#038; XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotations-one-to-many-mapping.html" title="Hibernate Self Join Annotations One To Many mapping example">Hibernate Self Join Annotations One To Many mapping example</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html" title="Hibernate Many To Many Annotation Mapping Tutorial">Hibernate Many To Many Annotation Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-xml-mapping-tutorial.html" title="Hibernate One To Many XML Mapping Tutorial">Hibernate One To Many XML Mapping Tutorial</a></li></ul></div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=E_nyG570x70:8Zmf6hcm5eA:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=E_nyG570x70:8Zmf6hcm5eA:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=E_nyG570x70:8Zmf6hcm5eA:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?i=E_nyG570x70:8Zmf6hcm5eA:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=E_nyG570x70:8Zmf6hcm5eA:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=E_nyG570x70:8Zmf6hcm5eA:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=I9og5sOYxJI" border="0"></img></a>
</div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2012/05/org-hibernate-annotationexception-no-identifier-specified.html/feed</wfw:commentRss> <slash:comments>0</slash:comments> <feedburner:origLink>http://viralpatel.net/blogs/2012/05/org-hibernate-annotationexception-no-identifier-specified.html</feedburner:origLink></item> <item><title>Android: Trigger Media Scanner Programmatically</title><link>http://feedproxy.google.com/~r/viralpatelnet/~3/7Ut_A8fQQwo/android-trigger-media-scanner-api.html</link> <comments>http://viralpatel.net/blogs/2012/05/android-trigger-media-scanner-api.html#comments</comments> <pubDate>Mon, 07 May 2012 20:20:02 +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=2735</guid> <description><![CDATA[While working on an Android App, I had to integrate the Camera API. User can take a photo from App and process it. With Android the Photo that you click cannot be accessed until the media scanner runs and index it. It is possible to triggeer programatically the Media Scanner in Android. Check the below [...]]]></description> <content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/no0hI6kxZFId1XC_F107KYhwAF8/0/da"><img src="http://feedads.g.doubleclick.net/~a/no0hI6kxZFId1XC_F107KYhwAF8/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/no0hI6kxZFId1XC_F107KYhwAF8/1/da"><img src="http://feedads.g.doubleclick.net/~a/no0hI6kxZFId1XC_F107KYhwAF8/1/di" border="0" ismap="true"></img></a></p><p>While working on an Android App, I had to integrate the Camera API. User can take a photo from App and process it. With Android the Photo that you click cannot be accessed until the media scanner runs and index it. It is possible to triggeer programatically the Media Scanner in Android. Check the below code snippet:</p><pre class="brush: java; title: ; notranslate">
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
...
...
sendBroadcast( new Intent(Intent.ACTION_MEDIA_MOUNTED,
						Uri.parse(&quot;file://&quot; + Environment.getExternalStorageDirectory()))
			);
...
</pre><p>Here we are using sendBroadcast method from Activity class to send a broadcast message to an Intent. For our need we have used <strong>ACTION_MEDIA_MOUNTED</strong> intent which will invoke the media scanner. Also note that we have passed the path (URI) of our external storage directory.</p><p>So in your app whenever you want to trigger Media scanner, simply invoke the above intent via broadcast message.</p><p>Following is a Demo App to achieve this.</p><h2>Demo App</h2><p>The App will be very simple. It will have a button <strong>&#8220;Trigger Media Scanner&#8221;</strong>. On its click we will invoke the above <strong>sendBroadcast()</strong> code to trigger media scanner.</p><h2>Step 1: Create Basic Android Project in Eclipse</h2><p>Create a Hello World Android project in Eclipse. Go to <strong>New &gt; Project &gt; Android Project</strong>. Give the project name as <strong>MediaScannerDemo</strong> and select Android Runtime 2.1 or sdk 7. I have given package name <code>net.viralpatel.android.mediascanner</code>.</p><p>Once you are done with above steps, you will have a basic hello world Android App.</p><h2>Step 2: Change the Layout</h2><p>For our demo, we need simple layout. Just one button <strong>Trigger Image Scanner</strong> which does the job.</p><p>Open layout/main.xml in your android project and replace its content with following:</p><p><em>File: res/layout/main.xml</em></p><pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:orientation=&quot;vertical&quot;
    android:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot;
    android:gravity=&quot;center&quot;&gt;

    &lt;Button
    		android:id=&quot;@+id/buttonMediaScanner&quot;
    		android:layout_width=&quot;fill_parent&quot;
    		android:text=&quot;Trigger Media Scanner&quot;
    		android:textSize=&quot;25dp&quot;
    		android:layout_height=&quot;100dp&quot;&gt;&lt;/Button&gt;

&lt;/LinearLayout&gt;
</pre><p>The UI is very simply. One LinearLayout to organize the button and one button. Note the id for button <code>buttonMediaScanner</code> which we will use in our Java code.</p><h2>Step 3: Android Java Code to trigger Image Scanner Intent</h2><p>Open <code>MediaScannerDemoActivity</code> class and add following code in <code>OnCreate()</code> method.</p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.android.mediascanner;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MediaScannerDemoActivity extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		Button buttonMediaScanner = (Button) findViewById(R.id.buttonMediaScanner);

		//Add onClick event on Media scanner button
		buttonMediaScanner.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {

				//Broadcast the Media Scanner Intent to trigger it
				sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri
						.parse(&quot;file://&quot;
								+ Environment.getExternalStorageDirectory())));

				//Just a message
				Toast toast = Toast.makeText(getApplicationContext(),
						&quot;Media Scanner Triggered...&quot;, Toast.LENGTH_SHORT);
				toast.show();
			}
		});

	}
}
</pre><p>Thus in <code>OnCreate()</code> method, we have added an <code>OnClickListener</code> to button. In the listener class, we added logic to trigger media scanner and also a Toast message to show user that scanner has been triggered.</p><h2>Screen shots of Android App</h2><p>And that&#8217;s all! Just execute the app in Android emulator or real device and see following output.</p><p><img src="http://img.viralpatel.net/2012/05/android-media-scanner-trigger.png" alt="android-media-scanner-trigger" title="android-media-scanner-trigger" width="240" height="400" class="aligncenter size-full wp-image-2757" /></p><p>On click of Trigger Media Scanner button, the media scanner is invoked which we can see in Title bar.<br /> <img src="http://img.viralpatel.net/2012/05/media-scanner-app.png" alt="android media-scanner-app" title="media-scanner-app" width="240" height="400" class="aligncenter size-full wp-image-2756" /></p><h2>Download Source Code</h2><p><a href="http://viralpatel-net-tutorials.googlecode.com/files/MediaScannerDemo.zip"><strong>MediaScannerDemo.zip (45 KB)</strong></a></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2012/05/pick-image-from-galary-android-app.html" 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/2012/05/enable-camera-in-android-emulator.html" title="How To Enable Camera in Android Emulator">How To Enable Camera in Android Emulator</a></li></ul></div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=7Ut_A8fQQwo:Ynm87F3DgbM:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=7Ut_A8fQQwo:Ynm87F3DgbM:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=7Ut_A8fQQwo:Ynm87F3DgbM:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?i=7Ut_A8fQQwo:Ynm87F3DgbM:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=7Ut_A8fQQwo:Ynm87F3DgbM:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=7Ut_A8fQQwo:Ynm87F3DgbM:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=I9og5sOYxJI" border="0"></img></a>
</div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2012/05/android-trigger-media-scanner-api.html/feed</wfw:commentRss> <slash:comments>0</slash:comments> <feedburner:origLink>http://viralpatel.net/blogs/2012/05/android-trigger-media-scanner-api.html</feedburner:origLink></item> <item><title>How To Enable Camera in Android Emulator</title><link>http://feedproxy.google.com/~r/viralpatelnet/~3/YqPr47WoR6c/enable-camera-in-android-emulator.html</link> <comments>http://viralpatel.net/blogs/2012/05/enable-camera-in-android-emulator.html#comments</comments> <pubDate>Mon, 07 May 2012 20:05:40 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Android]]></category> <category><![CDATA[android]]></category> <category><![CDATA[android emulator]]></category> <category><![CDATA[android sdk]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2722</guid> <description><![CDATA[By default when you create an Android Virtual Devices (AVD) in Android, the Camera is disabled. So if your application uses Camera API, it might not work properly in Android Emulator. Also SDCard must be defined in emulator in order to use Camera. To enable Camera in your Android Emulator, just add following highlighted code [...]]]></description> <content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/a68BViZG_V0wgK6I6AXHxytZkik/0/da"><img src="http://feedads.g.doubleclick.net/~a/a68BViZG_V0wgK6I6AXHxytZkik/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/a68BViZG_V0wgK6I6AXHxytZkik/1/da"><img src="http://feedads.g.doubleclick.net/~a/a68BViZG_V0wgK6I6AXHxytZkik/1/di" border="0" ismap="true"></img></a></p><p>By default when you create an Android Virtual Devices (AVD) in Android, the Camera is disabled. So if your application uses Camera API, it might not work properly in Android Emulator. Also SDCard must be defined in emulator in order to use Camera.</p><p>To enable Camera in your Android Emulator, just add following highlighted code in your AVD&#8217;s <code>config.ini</code> file. You can find the config.ini file under your <em>user directory/.android</em> folder.</p><p><em>File: ~/.android/config.ini</em></p><pre class="brush: plain; highlight: [8,9]; title: ; notranslate">
hw.lcd.density=160
skin.name=HVGA
skin.path=platforms\android-9\skins\HVGA
hw.cpu.arch=arm
abi.type=armeabi
vm.heapSize=24
image.sysdir.1=platforms\android-9\images\
hw.camera=yes
sdcard.size=64M
...
...
</pre><p>In case you don&#8217;t find the config.ini file or want to enable Camera support through <strong>Android SDK and AVD Manager</strong>, follow below simple steps.</p><p>Open Android SDK and AVD Manager:</p><h2>Step 1: Add SD Card in AVD</h2><p>In the SD Card setting, set the value for <strong>Size</strong>. To enable camera, the SD Card must be enabled in Emulator.<br /> <img src="http://img.viralpatel.net/2012/05/android-avd-sdcard-size.png" alt="android-emulator-sdcard-size" title="android-avd-sdcard-size" width="312" height="494" class="alignnone size-full wp-image-2728" /></p><h2>Step 2: Add Camera Support in Hardware under AVD</h2><p>Now under <em>Hardware</em> section, click <strong>New</strong> button to add Camera hardware. It will open following Dialog box. Select <strong>Camera support</strong> from the Property dropdown and click Ok.<br /> <img src="http://img.viralpatel.net/2012/05/android-avd-hardware-camera-support.png" alt="android-emulator-hardware-camera-support" title="android-avd-hardware-camera-support" width="320" height="184" class="alignnone size-full wp-image-2729" /></p><h2>Step 3: Enable Camera Support in Hardware</h2><p>The new hardware: Camera support is visible under Hardware section. Set its value to <strong>yes</strong> and save changes by pressing <strong>Edit AVD</strong>.<br /> <img src="http://img.viralpatel.net/2012/05/android-emulator-camera-enable-yes.png" alt="android-emulator-camera-enable-yes" title="android-emulator-camera-enable-yes" width="312" height="494" class="alignnone size-full wp-image-2727" /></p><p>And that&#8217;s all. Just save the changes and launch the emulator. You&#8217;ll be able to start Camera application and take snaps (Default android pic) through it.</p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2012/05/android-trigger-media-scanner-api.html" title="Android: Trigger Media Scanner Programmatically">Android: Trigger Media Scanner Programmatically</a></li><li><a href="http://viralpatel.net/blogs/2012/05/pick-image-from-galary-android-app.html" 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/2009/04/google-android-adt-sdk-and-eclipse-ide-integration-on-linux.html" 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/2009/04/android-15-released-sdk-feature-list-android-google.html" title="Android 1.5 released: Preview SDK &#038; feature list">Android 1.5 released: Preview SDK &#038; feature list</a></li></ul></div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=YqPr47WoR6c:HRWeTRm4yRc:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=YqPr47WoR6c:HRWeTRm4yRc:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=YqPr47WoR6c:HRWeTRm4yRc:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?i=YqPr47WoR6c:HRWeTRm4yRc:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=YqPr47WoR6c:HRWeTRm4yRc:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=YqPr47WoR6c:HRWeTRm4yRc:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=I9og5sOYxJI" border="0"></img></a>
</div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2012/05/enable-camera-in-android-emulator.html/feed</wfw:commentRss> <slash:comments>0</slash:comments> <feedburner:origLink>http://viralpatel.net/blogs/2012/05/enable-camera-in-android-emulator.html</feedburner:origLink></item> <item><title>How to Resize Image Dynamically in PHP</title><link>http://feedproxy.google.com/~r/viralpatelnet/~3/lP8LnD4sqo0/resize-image-dynamically-php.html</link> <comments>http://viralpatel.net/blogs/2012/05/resize-image-dynamically-php.html#comments</comments> <pubDate>Thu, 03 May 2012 18:42:53 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[PHP]]></category> <category><![CDATA[php code snippet]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2709</guid> <description><![CDATA[Today almost every website you visit show content in form of thumbnails. Thumbnails are nothing but images displayed next to the content. Be it News website or a blog, displaying images next to content is key to appeal user. Even our blog shows images as thumbnails on home page. A prerequisites to show Thumbnail in [...]]]></description> <content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/FR8dvq8QFotSHvuX_F-4cQacpOE/0/da"><img src="http://feedads.g.doubleclick.net/~a/FR8dvq8QFotSHvuX_F-4cQacpOE/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/FR8dvq8QFotSHvuX_F-4cQacpOE/1/da"><img src="http://feedads.g.doubleclick.net/~a/FR8dvq8QFotSHvuX_F-4cQacpOE/1/di" border="0" ismap="true"></img></a></p><p><img src="http://img.viralpatel.net/2009/05/php-logo.png" alt="resize-image-dynamically-php" title="php-logo" width="227" height="120" class="alignright size-full wp-image-1247" />Today almost every website you visit show content in form of thumbnails. Thumbnails are nothing but images displayed next to the content. Be it News website or a blog, displaying images next to content is key to appeal user. Even our blog shows images as thumbnails on home page.</p><p>A prerequisites to show Thumbnail in a webpage is that thumbnail must be small enough. So that many thumbnails can be loaded as fast as possible. Hence almost every website resize the image to create small thumbnails.</p><p>So how to do this on the fly? How to resize an Image dynamically in PHP?</p><p>There is an extremely useful PHP library called <strong><a rel="nofollow" target="_new" href="http://code.google.com/p/timthumb/">timthumb</a></strong> which comes very handy. It&#8217;s just a simple PHP script that you need to download and put in some folder under your website. And then simply call it with appropriate arguments.</p><ol><li>Download <a rel="nofollow" target="_new" href="http://timthumb.googlecode.com/svn/trunk/timthumb.php">timthumb.php</a> and put under any folder.</li><li>Upload this script <code>timthumb.php</code> though FTP to your web hosting. Put it under a directory <code>/script</code>.</li><li>Just call timthumb.php with appropriate arguments, For example:<pre class="brush: xml; title: ; notranslate">
&lt;img src=&quot;/script/timthumb.php?src=/some/path/myimage.png&amp;w=100&amp;h=80&quot;
	alt=&quot;resized image&quot; /&gt;
</pre></li></ol><p>And that&#8217;s all!!</p><p>One thing worth noting here is that this library will create a folder <strong>cache</strong> in the directory where timthumb.php script resides. This folder will cache the resized image for better performance.</p><p>You can refer following table for different parameters and its meaning.</p><style>table.article{border:1px
solid;border-collapse:collapse}table.article tr
td{border:1px
solid;padding:2px}table.article tr
th{border:1px
solid;padding:5px}</style><table class="article"><tbody><tr><th></th><th>Parameter</th><th>Values</th><th>Meaning</th></tr><tr><td>src</td><td>source</td><td>url to image</td><td>Tells TimThumb which image to resize</td></tr><tr><td>w</td><td>width</td><td>the width to resize to</td><td>Remove the width to scale proportionally (will then need the height)</td></tr><tr><td>h</td><td>height</td><td>the height to resize to</td><td>Remove the height to scale proportionally (will then need the width)</td></tr><tr><td>q</td><td>quality</td><td>0 &#8211; 100</td><td>Compression quality. The higher the number the nicer the image will look. I wouldn&#8217;t recommend going any higher than about 95 else the image will get too large</td></tr><tr><td>a</td><td>alignment</td><td>c, t, l, r, b, tl, tr, bl, br</td><td>Crop alignment. c = center, t = top, b = bottom, r = right, l = left. The positions can be joined to create diagonal positions</td></tr><tr><td>zc</td><td>zoom / crop</td><td>0, 1, 2, 3</td><td>Change the cropping and scaling settings</td></tr><tr><td>f</td><td>filters</td><td>too many to mention</td><td>Let&#8217;s you apply image filters to change the resized picture. For instance you can change brightness/ contrast or even blur the image</td></tr><tr><td>s</td><td>sharpen</td><td></td><td>Apply a sharpen filter to the image, makes scaled down images look a little crisper</td></tr><tr><td>cc</td><td>canvas colour</td><td>hexadecimal colour value (#ffffff)</td><td>Change background colour. Most used when changing the zoom and crop settings, which in turn can add borders to the image.</td></tr><tr><td>ct</td><td>canvas transparency</td><td>true (1)</td><td>Use transparency and ignore background colour</td></tr></tbody></table><p>Hope this is useful for you <img src='http://viralpatel.net/blogs/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/06/twitter-like-n-min-sec-ago-timestamp-in-php-mysql.html" title="Twitter like N min/sec ago timestamp in PHP/MySQL">Twitter like N min/sec ago timestamp in PHP/MySQL</a></li><li><a href="http://viralpatel.net/blogs/2009/05/15-very-useful-php-code-snippets-for-php-developers.html" title="15 very useful PHP code snippets for PHP developers">15 very useful PHP code snippets for PHP developers</a></li><li><a href="http://viralpatel.net/blogs/2011/01/dynamic-unread-count-favicon-in-php.html" title="Dynamic unread count Favicon in PHP">Dynamic unread count Favicon in PHP</a></li><li><a href="http://viralpatel.net/blogs/2010/12/password-protect-your-webpages-using-htaccess.html" title="Password Protect your webpages using htaccess">Password Protect your webpages using htaccess</a></li><li><a href="http://viralpatel.net/blogs/2009/11/php-fatal-error-time-htaccess.html" title="PHP Fatal Error Maximum Execution Time Issue &#038; htaccess">PHP Fatal Error Maximum Execution Time Issue &#038; htaccess</a></li><li><a href="http://viralpatel.net/blogs/2009/09/how-to-setup-multiple-virtual-hosts-in-wamp.html" title="How to: Setup Multiple Virtual Hosts in WAMP Server">How to: Setup Multiple Virtual Hosts in WAMP Server</a></li><li><a href="http://viralpatel.net/blogs/2009/08/server-php-variable-php-self-server-request-uri.html" title="Knowing $_SERVER PHP Variable in a better way">Knowing $_SERVER PHP Variable in a better way</a></li></ul></div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=lP8LnD4sqo0:WP3fCI2t-gU:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=lP8LnD4sqo0:WP3fCI2t-gU:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=lP8LnD4sqo0:WP3fCI2t-gU:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?i=lP8LnD4sqo0:WP3fCI2t-gU:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=lP8LnD4sqo0:WP3fCI2t-gU:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=lP8LnD4sqo0:WP3fCI2t-gU:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=I9og5sOYxJI" border="0"></img></a>
</div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2012/05/resize-image-dynamically-php.html/feed</wfw:commentRss> <slash:comments>0</slash:comments> <feedburner:origLink>http://viralpatel.net/blogs/2012/05/resize-image-dynamically-php.html</feedburner:origLink></item> <item><title>How To Pick Image From Gallery in Android App</title><link>http://feedproxy.google.com/~r/viralpatelnet/~3/eLn34bvmqio/pick-image-from-galary-android-app.html</link> <comments>http://viralpatel.net/blogs/2012/05/pick-image-from-galary-android-app.html#comments</comments> <pubDate>Thu, 03 May 2012 08:59:51 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Android]]></category> <category><![CDATA[android]]></category> <category><![CDATA[android-intent]]></category> <category><![CDATA[image-gallery]]></category> <category><![CDATA[java code]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2684</guid> <description><![CDATA[Since few days I am working on an Android app and learning all the nitty gritty of its APIs. I will share few How-to stuffs that we frequently require in Android. To start with let us see how to integrate Image Gallery with your App. Consider a requirement, you want your app user to select [...]]]></description> <content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/nekl4-LxzYQ7nK_ZMIbYddT9oGI/0/da"><img src="http://feedads.g.doubleclick.net/~a/nekl4-LxzYQ7nK_ZMIbYddT9oGI/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/nekl4-LxzYQ7nK_ZMIbYddT9oGI/1/da"><img src="http://feedads.g.doubleclick.net/~a/nekl4-LxzYQ7nK_ZMIbYddT9oGI/1/di" border="0" ismap="true"></img></a></p><p>Since few days I am working on an Android app and learning all the nitty gritty of its APIs. I will share few How-to stuffs that we frequently require in Android.</p><p>To start with let us see how to integrate Image Gallery with your App. Consider a requirement, you want your app user to select Image from the Gallery and use that image to do some stuff. For example, in Facebook app you can select Picture from your phone and upload directly to your profile.</p><p>Let us create an example with following requirement:</p><ol><li>First screen shows user with and Image view and a button to loan Picture.</li><li>On click of &#8220;Load Picture&#8221; button, user will be redirected to Android&#8217;s Image Gallery where she can select one image.</li><li>Once the image is selected, the image will be loaded in Image view on main screen.</li></ol><p>So lets start.</p><h2>Step 1: Create Basic Android Project in Eclipse</h2><p>Create a Hello World Android project in Eclipse. Go to <strong>New &gt; Project &gt; Android Project</strong>. Give the project name as <strong>ImageGalleryDemo</strong> and select Android Runtime 2.1 or sdk 7.</p><p>Once you are done with above steps, you will have a basic hello world Android App.</p><h2>Step 2: Change the Layout</h2><p>For our demo, we need simple layout. One Image view to display user selected image and one button to trigger Image gallery.</p><p>Open layout/main.xml in your android project and replace its content with following:</p><p><em>File: res/layout/main.xml</em></p><pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:orientation=&quot;vertical&quot;
    android:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot;&gt;
	&lt;ImageView
		android:id=&quot;@+id/imgView&quot;
		android:layout_width=&quot;fill_parent&quot;
		android:layout_height=&quot;wrap_content&quot;
		android:layout_weight=&quot;1&quot;&gt;&lt;/ImageView&gt;
	&lt;Button
		android:id=&quot;@+id/buttonLoadPicture&quot;
		android:layout_width=&quot;wrap_content&quot;
		android:layout_height=&quot;wrap_content&quot;
		android:layout_weight=&quot;0&quot;
		android:text=&quot;Load Picture&quot;
		android:layout_gravity=&quot;center&quot;&gt;&lt;/Button&gt;
&lt;/LinearLayout&gt;
</pre><p>So our Android&#8217;s app UI is very simple, One LinearLayout to organize Image view and Button linearly. Note that the id of Image view is <strong>imgView</strong> and that of Button is <strong>buttonLoadPicture</strong>.</p><h2>Step 3: Android Java Code to trigger Image Gallery Intent</h2><p>We now need to write some Java code to actually handle the button click. On click of buttonLoadPicture button, we need to trigger the intent for Image Gallery.</p><p>Thus, on click of button we will trigger following code:</p><pre class="brush: java; title: ; notranslate">
	Intent i = new Intent(
	Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

	startActivityForResult(i, RESULT_LOAD_IMAGE);
</pre><p>Note how we passed an integer <strong>RESULT_LOAD_IMAGE</strong> to <code>startActivityForResult()</code> method. This is to handle the result back when an image is selected from Image Gallery.</p><p>So the above code will trigger Image Gallery. But how to retrieve back the image selected by user in our main activity?</p><h2>Step 4: Getting back selected Image details in Main Activity</h2><p>Once user will select an image, the method <code>onActivityResult()</code> of our main activity will be called. We need to handle the data in this method as follows:</p><pre class="brush: java; title: ; notranslate">
   @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == RESULT_LOAD_IMAGE &amp;&amp; resultCode == RESULT_OK &amp;&amp; null != data) {
			Uri selectedImage = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };

			Cursor cursor = getContentResolver().query(selectedImage,
					filePathColumn, null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			String picturePath = cursor.getString(columnIndex);
			cursor.close();

			// String picturePath contains the path of selected Image
		}
</pre><p>Note that method onActivityResult gets called once an Image is selected. In this method, we check if the activity that was triggered was indeed Image Gallery (It is common to trigger different intents from the same activity and expects result from each). For this we used RESULT_LOAD_IMAGE integer that we passed previously to <code>startActivityForResult()</code> method.</p><h2>Final Code</h2><p>Below is the final code of <code>ImageGalleryDemoActivity</code> class.</p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.android.imagegalleray;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class ImageGalleryDemoActivity extends Activity {

	private static int RESULT_LOAD_IMAGE = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
        buttonLoadImage.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {

				Intent i = new Intent(
						Intent.ACTION_PICK,
						android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

				startActivityForResult(i, RESULT_LOAD_IMAGE);
			}
		});
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == RESULT_LOAD_IMAGE &amp;&amp; resultCode == RESULT_OK &amp;&amp; null != data) {
			Uri selectedImage = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };

			Cursor cursor = getContentResolver().query(selectedImage,
					filePathColumn, null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			String picturePath = cursor.getString(columnIndex);
			cursor.close();

			ImageView imageView = (ImageView) findViewById(R.id.imgView);
			imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

		}

    }
}
</pre><h2>Screen shots of Android app</h2><p><b>First screen: Lets user to trigger Image Gallery</b><br /> <img src="http://img.viralpatel.net/2012/05/android-gallery-intent-example.png" alt="android-gallery-intent-example" title="android-gallery-intent-example" width="240" height="400" class="aligncenter size-full wp-image-2698" /></p><p><b>User can select an image from Image Gallery</b><br /> <img src="http://img.viralpatel.net/2012/05/android-gallery-intent-select-image.png" alt="android-gallery-intent-select-image" title="android-gallery-intent-select-image" width="240" height="400" class="aligncenter size-full wp-image-2699" /></p><p><b>Once user selects an image, the same will be displayed on our main activity</b><br /> <img src="http://img.viralpatel.net/2012/05/android-gallery-intent-example-demo.png" alt="android-gallery-intent-example-demo" title="android-gallery-intent-example-demo" width="240" height="400" class="aligncenter size-full wp-image-2697" /></p><h2>Download Source Code</h2><p><a href="http://viralpatel-net-tutorials.googlecode.com/files/ImageGalleryDemo.zip"><strong>ImageGalleryDemo.zip (46 KB)</strong></a></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2012/05/android-trigger-media-scanner-api.html" title="Android: Trigger Media Scanner Programmatically">Android: Trigger Media Scanner Programmatically</a></li><li><a href="http://viralpatel.net/blogs/2012/05/enable-camera-in-android-emulator.html" title="How To Enable Camera in Android Emulator">How To Enable Camera in Android Emulator</a></li><li><a href="http://viralpatel.net/blogs/2012/05/iterate-hashmap-in-freemarker-ftl.html" title="How To Iterate HashMap in FreeMarker (FTL)">How To Iterate HashMap in FreeMarker (FTL)</a></li><li><a href="http://viralpatel.net/blogs/2012/03/batch-insert-in-java-jdbc.html" title="Batch Insert In Java &#8211; JDBC">Batch Insert In Java &#8211; JDBC</a></li><li><a href="http://viralpatel.net/blogs/2012/01/create-qr-codes-java-servlet-qr-code-java.html" title="How To Create QR Codes in Java &#038; Servlet">How To Create QR Codes in Java &#038; Servlet</a></li><li><a href="http://viralpatel.net/blogs/2010/07/java-calculate-free-disk-space-java-apache-commons-io.html" title="Calculate Free Disk Space in Java using Apache Commons IO">Calculate Free Disk Space in Java using Apache Commons IO</a></li><li><a href="http://viralpatel.net/blogs/2009/06/convert-arraylist-to-arrays-in-java.html" title="Convert ArrayList to Arrays in Java">Convert ArrayList to Arrays in Java</a></li></ul></div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=eLn34bvmqio:jkhqoylt5Hs:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=eLn34bvmqio:jkhqoylt5Hs:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=eLn34bvmqio:jkhqoylt5Hs:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?i=eLn34bvmqio:jkhqoylt5Hs:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=eLn34bvmqio:jkhqoylt5Hs:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=eLn34bvmqio:jkhqoylt5Hs:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=I9og5sOYxJI" border="0"></img></a>
</div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2012/05/pick-image-from-galary-android-app.html/feed</wfw:commentRss> <slash:comments>0</slash:comments> <feedburner:origLink>http://viralpatel.net/blogs/2012/05/pick-image-from-galary-android-app.html</feedburner:origLink></item> <item><title>How To Iterate HashMap in FreeMarker (FTL)</title><link>http://feedproxy.google.com/~r/viralpatelnet/~3/vPdH3eD0lYQ/iterate-hashmap-in-freemarker-ftl.html</link> <comments>http://viralpatel.net/blogs/2012/05/iterate-hashmap-in-freemarker-ftl.html#comments</comments> <pubDate>Wed, 02 May 2012 10:23:54 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Java]]></category> <category><![CDATA[Freemarker]]></category> <category><![CDATA[FTL]]></category> <category><![CDATA[java code]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2691</guid> <description><![CDATA[In this short article we will see how to iterate an HashMap in FreeMarker template. Consider below code which is normally used to iterate a List in FTL. Output: Here in above code, we created a List object and passed it to FTL page. In FTL we used to iterate and print its values. Problem [...]]]></description> <content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/TRsh1GiESOnuoD5_146D--vIeCw/0/da"><img src="http://feedads.g.doubleclick.net/~a/TRsh1GiESOnuoD5_146D--vIeCw/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/TRsh1GiESOnuoD5_146D--vIeCw/1/da"><img src="http://feedads.g.doubleclick.net/~a/TRsh1GiESOnuoD5_146D--vIeCw/1/di" border="0" ismap="true"></img></a></p><p>In this short article we will see how to iterate an <code>HashMap</code> in FreeMarker template. Consider below code which is normally used to iterate a <code>List</code> in FTL.</p><pre class="brush: java; title: ; notranslate">
//Java
List&lt;String&gt; cityList = new ArrayList&lt;String&gt;();
cityList.add(&quot;Washington DC&quot;);
cityList.add(&quot;Delhi&quot;);
cityList.add(&quot;Berlin&quot;);
cityList.add(&quot;Paris&quot;);
cityList.add(&quot;Rome&quot;);

request.setAttribute(&quot;cityList&quot;, cityList);

//FTL template
&lt;#list cityList as city&gt;
    &lt;b&gt; ${city} &lt;/b&gt;
&lt;/#list&gt;
</pre><p><strong>Output:</strong></p><pre class="brush: plain; title: ; notranslate">
Washington DC
Delhi
Berlin
Paris
Rome
</pre><p>Here in above code, we created a <code>List</code> object and passed it to FTL page. In FTL we used <code><#list></code> to iterate and print its values.</p><h3>Problem Statement</h3><p>So here&#8217;s the problem statement. I have an Hashmap which I want to iterate and display in my FTL (FreeMarker) template. Consider following code in Java.</p><p>So how to iterate this Hashmap in FTL and display its values?</p><pre class="brush: java; title: ; notranslate">
//Java
Map&lt;String, String&gt; countryCapitalList = new HashMap&lt;String, String&gt;();
countryCapitalList.put(&quot;United States&quot;, &quot;Washington DC&quot;);
countryCapitalList.put(&quot;India&quot;, &quot;Delhi&quot;);
countryCapitalList.put(&quot;Germany&quot;, &quot;Berlin&quot;);
countryCapitalList.put(&quot;France&quot;, &quot;Paris&quot;);
countryCapitalList.put(&quot;Italy&quot;, &quot;Rome&quot;);

request.setAttribute(&quot;capitalList&quot;, countryCapitalList);
</pre><h3>Solution</h3><p>Well, the above hashmap can be iterated in FTL using following code:</p><pre class="brush: java; title: ; notranslate">
&lt;#list capitalList?keys as key&gt;
    ${key} = ${capitalList[key]}
&lt;/#list&gt;
</pre><p><strong>Output:</strong></p><pre class="brush: plain; title: ; notranslate">
United States = Washington DC
India = Delhi
Germany = Berlin
France = Paris
Italy = Rome
</pre><p>In above code, we used <em>?keys</em> attribute to get the <code>keySet</code> of <code>HashMap</code>. This key set is iterated and corresponding value is fetched by <code>user.get(key)</code> method.</p><p><strong>Note:</strong> One thing that&#8217;s worth noting here is that the sequence in which the values are printing may be different then the actual sequence in which values are added in hashmap. This is because, hashmap doesn&#8217;t preserve order or values. If you want to preserve the sequence of keys use <code>LinkedHashMap</code>.</p><p>Hope this helps.</p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2012/05/pick-image-from-galary-android-app.html" 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/2012/03/batch-insert-in-java-jdbc.html" title="Batch Insert In Java &#8211; JDBC">Batch Insert In Java &#8211; JDBC</a></li><li><a href="http://viralpatel.net/blogs/2012/01/create-qr-codes-java-servlet-qr-code-java.html" title="How To Create QR Codes in Java &#038; Servlet">How To Create QR Codes in Java &#038; Servlet</a></li><li><a href="http://viralpatel.net/blogs/2010/07/java-calculate-free-disk-space-java-apache-commons-io.html" title="Calculate Free Disk Space in Java using Apache Commons IO">Calculate Free Disk Space in Java using Apache Commons IO</a></li><li><a href="http://viralpatel.net/blogs/2009/06/convert-arraylist-to-arrays-in-java.html" title="Convert ArrayList to Arrays in Java">Convert ArrayList to Arrays in Java</a></li><li><a href="http://viralpatel.net/blogs/2009/06/double-brace-initialization-in-java.html" title="Double Brace Initialization in Java!">Double Brace Initialization in Java!</a></li><li><a href="http://viralpatel.net/blogs/2009/05/varargs-in-java-variable-argument-method-in-java-5.html" title="Varargs in Java: Variable argument method in Java 5">Varargs in Java: Variable argument method in Java 5</a></li></ul></div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=vPdH3eD0lYQ:GDBGWSB70nA:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=vPdH3eD0lYQ:GDBGWSB70nA:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=vPdH3eD0lYQ:GDBGWSB70nA:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?i=vPdH3eD0lYQ:GDBGWSB70nA:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=vPdH3eD0lYQ:GDBGWSB70nA:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=vPdH3eD0lYQ:GDBGWSB70nA:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=I9og5sOYxJI" border="0"></img></a>
</div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2012/05/iterate-hashmap-in-freemarker-ftl.html/feed</wfw:commentRss> <slash:comments>0</slash:comments> <feedburner:origLink>http://viralpatel.net/blogs/2012/05/iterate-hashmap-in-freemarker-ftl.html</feedburner:origLink></item> <item><title>Batch Insert In Java – JDBC</title><link>http://feedproxy.google.com/~r/viralpatelnet/~3/1sVA-KjYQQw/batch-insert-in-java-jdbc.html</link> <comments>http://viralpatel.net/blogs/2012/03/batch-insert-in-java-jdbc.html#comments</comments> <pubDate>Thu, 01 Mar 2012 13:32:29 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Java]]></category> <category><![CDATA[database queries]]></category> <category><![CDATA[java code]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2672</guid> <description><![CDATA[Let&#8217;s see how we can perform batch insert in Java using JDBC APIs. Although you might already knew this, I will try to explain the basic to a bit complex scenarios. In this note, we will see how we can use JDBC APIs like Statement and PreparedStatement to insert data in any database in batches. [...]]]></description> <content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/gv9BjKlRrP4hI0Cqo-TwM88rRSM/0/da"><img src="http://feedads.g.doubleclick.net/~a/gv9BjKlRrP4hI0Cqo-TwM88rRSM/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/gv9BjKlRrP4hI0Cqo-TwM88rRSM/1/da"><img src="http://feedads.g.doubleclick.net/~a/gv9BjKlRrP4hI0Cqo-TwM88rRSM/1/di" border="0" ismap="true"></img></a></p><p><img src="http://img.viralpatel.net/2009/05/java-logo-cup.jpg" alt="" title="java-logo-cup" width="75" height="100" class="alignright size-full wp-image-1289" />Let&#8217;s see how we can perform batch insert in Java using JDBC APIs. Although you might already knew this, I will try to explain the basic to a bit complex scenarios.</p><p>In this note, we will see how we can use JDBC APIs like <code>Statement</code> and <code>PreparedStatement</code> to insert data in any database in batches. Also we will try to explore scenarios where we can run out of memory and how to optimize the batch operation.</p><p>So first, the basic API to Insert data in database in batches using Java JDBC.</p><h2>Simple Batch</h2><p>I am calling this a simple batch. The requirement is simple. Execute a list of inserts in batch. Instead of hitting database once for each insert statement, we will using JDBC batch operation and optimize the performance.</p><p>Consider the following code:</p><h3>Bad Code</h3><pre class="brush: java; title: ; notranslate">
String [] queries = {
	&quot;insert into employee (name, city, phone) values ('A', 'X', '123')&quot;,
	&quot;insert into employee (name, city, phone) values ('B', 'Y', '234')&quot;,
	&quot;insert into employee (name, city, phone) values ('C', 'Z', '345')&quot;,
};

Connection connection = new getConnection();
Statement statemenet = connection.createStatement();

for (String query : queries) {
	statemenet.execute(query);
}
statemenet.close();
connection.close();
</pre><p>This is the BAD code. You are executing each query separately. This hits the database for each insert statement. Consider if you want to insert 1000 records. This is not a good idea.</p><p>We&#8217;ll below is the basic code to perform batch insert. Check it out:</p><h3>Good Code</h3><pre class="brush: java; highlight: [5,7]; title: ; notranslate">
Connection connection = new getConnection();
Statement statemenet = connection.createStatement();

for (String query : queries) {
	statemenet.addBatch(query);
}
statemenet.executeBatch();
statemenet.close();
connection.close();
</pre><p>Note how we used <code>addBatch()</code> method of Statement, instead of directly executing the query. And after adding all the queries we executed them in one go using <code>statement.executeBatch()</code> method. Nothing fancy, just a simple batch insert.</p><p>Note that we have taken the queries from a String array. Instead you may want to make it dynamically. For example:</p><pre class="brush: java; title: ; notranslate">
import java.sql.Connection;
import java.sql.Statement;

//...

Connection connection = new getConnection();
Statement statemenet = connection.createStatement();

for (Employee employee: employees) {
	String query = &quot;insert into employee (name, city) values('&quot;
			+ employee.getName() + &quot;','&quot; + employee.getCity + &quot;')&quot;;
	statemenet.addBatch(query);
}
statemenet.executeBatch();
statemenet.close();
connection.close();
</pre><p>Note how we are creating query dynamically using data from Employee object and adding it in batch to insert in one go. Perfect! isn&#8217;t it?</p><p>wait.. You must be thinking what about SQL Injection? Creating queries like this dynamically is very prone to SQL injection. And also the insert query has to be compiled each time.</p><p>Why not to use <code>PreparedStatement</code> instead of simple <code>Statement</code>. Yes, that can be the solution. Check out the below SQL Injection Safe Batch.</p><h2>SQL Injection Safe Batch</h2><p>Consider the following code:</p><pre class="brush: java; highlight: [6,8,15,17]; title: ; notranslate">
import java.sql.Connection;
import java.sql.PreparedStatement;

//...

String sql = &quot;insert into employee (name, city, phone) values (?, ?, ?)&quot;;
Connection connection = new getConnection();
PreparedStatement ps = connection.prepareStatement(sql);

for (Employee employee: employees) {

	ps.setString(1, employee.getName());
	ps.setString(2, employee.getCity());
	ps.setString(3, employee.getPhone());
	ps.addBatch();
}
ps.executeBatch();
ps.close();
connection.close();
</pre><p>Checkout the above code. Beautiful. We used <code>java.sql.PreparedStatement</code> and added insert query in the batch. This is the solution you must implement in your batch insert logic, instead of above <code>Statement</code> one.</p><p>Still there is one problem with this solution. Consider a scenario where you want to insert half million records into database using batch. Well, that may generate <strong>OutOfMemoryError</strong>:</p><pre class="brush: plain; title: ; notranslate">
java.lang.OutOfMemoryError: Java heap space
    com.mysql.jdbc.ServerPreparedStatement$BatchedBindValues.&lt;init&gt;(ServerPreparedStatement.java:72)
    com.mysql.jdbc.ServerPreparedStatement.addBatch(ServerPreparedStatement.java:330)
    org.apache.commons.dbcp.DelegatingPreparedStatement.addBatch(DelegatingPreparedStatement.java:171)
</pre><p>This is because you are trying to add everything in one batch and inserting once. Best idea would be to execute batch itself in batch. Check out the below solution.</p><h2>Smart Insert: Batch within Batch</h2><p>This is a simplest solution. Consider a batch size like 1000 and insert queries in the batches of 1000 queries at a time.</p><pre class="brush: java; highlight: [15,16,17]; title: ; notranslate">
String sql = &quot;insert into employee (name, city, phone) values (?, ?, ?)&quot;;
Connection connection = new getConnection();
PreparedStatement ps = connection.prepareStatement(sql);

final int batchSize = 1000;
int count = 0;

for (Employee employee: employees) {

	ps.setString(1, employee.getName());
	ps.setString(2, employee.getCity());
	ps.setString(3, employee.getPhone());
	ps.addBatch();

	if(++count % batchSize == 0) {
		ps.executeBatch();
	}
}
ps.executeBatch(); // insert remaining records
ps.close();
connection.close();
</pre><p>This would be the idea solution. This avoids SQL Injection and also takes care of out of memory issue. Check how we have incremented a counter <code>count</code> and once it reaches <code>batchSize</code> which is 1000, we call <code>executeBatch()</code>.</p><p>Hope this helps.</p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2010/07/java-calculate-free-disk-space-java-apache-commons-io.html" title="Calculate Free Disk Space in Java using Apache Commons IO">Calculate Free Disk Space in Java using Apache Commons IO</a></li><li><a href="http://viralpatel.net/blogs/2009/06/convert-arraylist-to-arrays-in-java.html" title="Convert ArrayList to Arrays in Java">Convert ArrayList to Arrays in Java</a></li><li><a href="http://viralpatel.net/blogs/2009/06/double-brace-initialization-in-java.html" title="Double Brace Initialization in Java!">Double Brace Initialization in Java!</a></li><li><a href="http://viralpatel.net/blogs/2009/05/varargs-in-java-variable-argument-method-in-java-5.html" title="Varargs in Java: Variable argument method in Java 5">Varargs in Java: Variable argument method in Java 5</a></li><li><a href="http://viralpatel.net/blogs/2009/05/20-useful-java-code-snippets-for-java-developers.html" 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/2012/05/pick-image-from-galary-android-app.html" 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/2012/05/iterate-hashmap-in-freemarker-ftl.html" title="How To Iterate HashMap in FreeMarker (FTL)">How To Iterate HashMap in FreeMarker (FTL)</a></li></ul></div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=1sVA-KjYQQw:qoGX5TKToys:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=1sVA-KjYQQw:qoGX5TKToys:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=1sVA-KjYQQw:qoGX5TKToys:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?i=1sVA-KjYQQw:qoGX5TKToys:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=1sVA-KjYQQw:qoGX5TKToys:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=1sVA-KjYQQw:qoGX5TKToys:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=I9og5sOYxJI" border="0"></img></a>
</div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2012/03/batch-insert-in-java-jdbc.html/feed</wfw:commentRss> <slash:comments>10</slash:comments> <feedburner:origLink>http://viralpatel.net/blogs/2012/03/batch-insert-in-java-jdbc.html</feedburner:origLink></item> <item><title>Convert Arrays to Set in Java</title><link>http://feedproxy.google.com/~r/viralpatelnet/~3/Tb0aZZoHu9I/convert-array-to-set-java-arraylist.html</link> <comments>http://viralpatel.net/blogs/2012/01/convert-array-to-set-java-arraylist.html#comments</comments> <pubDate>Tue, 24 Jan 2012 13:45:10 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Java]]></category> <category><![CDATA[arraylists]]></category> <category><![CDATA[java collections]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2655</guid> <description><![CDATA[Java Collection API is one of the most useful APIs used in any Java application. In my day to day Java coding routine, I have to deal with these APIs quite often. However sometime while working with Collection API, lot of developers end up writing unnecessary and mostly inefficient code. For example, to convert an [...]]]></description> <content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/UeeWnMTEFy8MOw_yAYnIShr3C4Q/0/da"><img src="http://feedads.g.doubleclick.net/~a/UeeWnMTEFy8MOw_yAYnIShr3C4Q/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/UeeWnMTEFy8MOw_yAYnIShr3C4Q/1/da"><img src="http://feedads.g.doubleclick.net/~a/UeeWnMTEFy8MOw_yAYnIShr3C4Q/1/di" border="0" ismap="true"></img></a></p><p><img src="http://img.viralpatel.net/java-logo1.gif" alt="java-logo" title="java-logo" width="100" height="160" class="alignright size-full wp-image-620" />Java Collection API is one of the most useful APIs used in any Java application. In my day to day Java coding routine, I have to deal with these APIs quite often.</p><p>However sometime while working with Collection API, lot of developers end up writing unnecessary and mostly inefficient code. For example, to convert an <strong>Java Array to ArrayList</strong>, I have seen people writing loops instead of simple <code>Arrays.asList()</code>.</p><p>Here is a simple writeup on <a href="http://viralpatel.net/blogs/2009/06/convert-arraylist-to-arrays-in-java.html"><strong>Converting Java Arrays to ArrayList</strong></a> that I wrote a while ago.</p><p>One of such simple requirement is to convert Java <strong>Arrays to Set</strong>. While working with Hibernate, I once had to convert a Java Arrays that we used to populate from UI and convert it into <code>Set</code>. While this is a simple task, most often one may end up writing for loop.</p><p>Here is a dead simple trick. Use below code to <strong>Convert Arrays to Set</strong> in Java.</p><pre class="brush: java; gutter: false; title: ; notranslate">
Set&lt;T&gt; mySet = new HashSet&lt;T&gt;(Arrays.asList(someArray));
</pre><p>Tanaa!!! Simple isn&#8217;t it. Its like <em>&#8220;I already knew that&#8221;</em> stuff.</p><p>Notice how we have used Generics also in above code snippet. Thus if you have an <code>ArrayList<Foo></code> than you can convert it to Set<Foo> with one simple line of code.</p><p>Checkout below example:</p><h3>Example: Java Array to Set</h3><pre class="brush: java; title: ; notranslate">
String [] countires = {&quot;India&quot;, &quot;Switzerland&quot;, &quot;Italy&quot;}; 

Set&lt;String&gt; set = new HashSet&lt;String&gt;(Arrays.asList(countires));
System.out.println(set);
</pre><p><strong>Output:</strong></p><pre class="brush: plain; gutter: false; title: ; notranslate">
[Italy, Switzerland, India]
</pre><p>Hope this is useful.</p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/06/convert-arraylist-to-arrays-in-java.html" title="Convert ArrayList to Arrays in Java">Convert ArrayList to Arrays in Java</a></li><li><a href="http://viralpatel.net/blogs/2010/07/java-tip-how-to-sort-array-in-java-java-util-arrays.html" title="Java Tip: How to Sort Arrays in Java using java.util.Arrays class">Java Tip: How to Sort Arrays in Java using java.util.Arrays class</a></li><li><a href="http://viralpatel.net/blogs/2012/03/batch-insert-in-java-jdbc.html" title="Batch Insert In Java &#8211; JDBC">Batch Insert In Java &#8211; JDBC</a></li><li><a href="http://viralpatel.net/blogs/2011/12/spring-mvc-multi-row-submit-java-list.html" title="Spring MVC: Multiple Row Form Submit using List of Beans">Spring MVC: Multiple Row Form Submit using List of Beans</a></li><li><a href="http://viralpatel.net/blogs/2011/01/java-convert-exponential-decimal-double-number.html" title="Java: Convert Exponential form to Decimal number format in Java ">Java: Convert Exponential form to Decimal number format in Java </a></li><li><a href="http://viralpatel.net/blogs/2010/10/convert-string-to-enum-instance-string-enum-java.html" title="Convert String to Enum Instance in Java">Convert String to Enum Instance in Java</a></li><li><a href="http://viralpatel.net/blogs/2010/07/java-calculate-free-disk-space-java-apache-commons-io.html" title="Calculate Free Disk Space in Java using Apache Commons IO">Calculate Free Disk Space in Java using Apache Commons IO</a></li></ul></div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=Tb0aZZoHu9I:TgmF4DvyY9I:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=Tb0aZZoHu9I:TgmF4DvyY9I:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=Tb0aZZoHu9I:TgmF4DvyY9I:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?i=Tb0aZZoHu9I:TgmF4DvyY9I:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=Tb0aZZoHu9I:TgmF4DvyY9I:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=Tb0aZZoHu9I:TgmF4DvyY9I:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=I9og5sOYxJI" border="0"></img></a>
</div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2012/01/convert-array-to-set-java-arraylist.html/feed</wfw:commentRss> <slash:comments>2</slash:comments> <feedburner:origLink>http://viralpatel.net/blogs/2012/01/convert-array-to-set-java-arraylist.html</feedburner:origLink></item> <item><title>STOP SOPA JQuery Plugin</title><link>http://feedproxy.google.com/~r/viralpatelnet/~3/mqE7NvUTFAg/stopsopa-jquery-plugin.html</link> <comments>http://viralpatel.net/blogs/2012/01/stopsopa-jquery-plugin.html#comments</comments> <pubDate>Wed, 18 Jan 2012 11:48:30 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[JavaScript]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2641</guid> <description><![CDATA[Right now, Internet is experiencing the biggest protest since its inception. We have seen people protesting against Companies, Government, Dictators etc. Also Internet has become their voices in form of Twitter &#038; Facebook. But today we saw something completely new. Major websites such as Wikipedia and Google are openly demonstrating their protest against new legislation [...]]]></description> <content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/ayfqDyF-GXbsIpUj82tjBtkuJLg/0/da"><img src="http://feedads.g.doubleclick.net/~a/ayfqDyF-GXbsIpUj82tjBtkuJLg/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/ayfqDyF-GXbsIpUj82tjBtkuJLg/1/da"><img src="http://feedads.g.doubleclick.net/~a/ayfqDyF-GXbsIpUj82tjBtkuJLg/1/di" border="0" ismap="true"></img></a></p><p><img src="http://img.viralpatel.net/2012/01/stop-sopa.png" alt="stop-sopa" title="stop-sopa" width="143" height="140" class="alignright size-full wp-image-2642" />Right now, Internet is experiencing the biggest protest since its inception. We have seen people protesting against Companies, Government, Dictators etc. Also Internet has become their voices in form of Twitter &#038; Facebook.</p><p>But today we saw something completely new. Major websites such as Wikipedia and Google are openly demonstrating their protest against new legislation bills SOPA and PIPA which is right now being voted in U.S. Congress. The Senate will begin voting on January 24th.</p><p>Well, if you do support the STOPSOPA cause here is a coolest thing to do. Add a black colored STOPSOPA banner on your website!!!!</p><p>Here&#8217;s is the deal. I have created a simple JQuery plugin which you can include at the end of your website. And voila!!! It adds black color banner on top of your webpage saying &#8220;<strong>I  support #STOPSOPA campaign. Do you?</strong>&#8221;</p><p>Just include below javascript at the end of webpage:</p><pre class="brush: jscript; title: ; notranslate">
&lt;script type=&quot;text/javascript&quot; src=&quot;http://viralpatel.net/stopsopa/jquery.stopsopa.js&quot;&gt;&lt;/script&gt;
&lt;script&gt;
	$(document).ready(function() { $(this).stopsopa() });
&lt;/script&gt;
</pre><p>That&#8217;s All!!</p><p>Please note that I haven&#8217;t tested this plugin for cross browsers. Let me know in case you find difficulties in adding.</p><style>.demobtns
a{background:-moz-linear-gradient(center top , #BDED82, #83CC29) repeat scroll 0 0 transparent;border:1px
solid #5F961A;border-radius:7px 7px 7px 7px;color:#5F961A;display:inline-block;font-size:18px;margin-right:5px;padding:10px
9px}</style><div class="demobtns"> <a target="_new" href="http://viralpatel.net/stopsopa/">Demo</a></div><p><br/></p><h2>StopSOPA WordPress Plugin</h2><p>I have quickly assemble a small wordpress plugin to add StopSOPA message on your blog. Just in case you dont want to hack your lovely theme and add those javascripts, you can simply enable this plugin and voila; you have your own StopSOPA Blackout message.</p><p><strong>Update:</strong> The StopSOPA plugin is now available at WordPress Plugin Directory: <a rel="nofollow" href="http://wordpress.org/extend/plugins/stopsopa/"><strong>StopSOPA WP Plugin</strong></a></p><div class="demobtns"> <a target="_new" href="http://viralpatel.net/stopsopa/stopsopa.zip">Download StopSOPA Plugin</a></div><p><br/></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2012/05/javascript-delete-multiple-values-options-listbox.html" title="Deleting Multiple Values From Listbox in JavaScript">Deleting Multiple Values From Listbox in JavaScript</a></li><li><a href="http://viralpatel.net/blogs/2012/01/create-zip-file-javascript.html" title="Create ZIP Files in JavaScript">Create ZIP Files in JavaScript</a></li><li><a href="http://viralpatel.net/blogs/2010/11/multiple-checkbox-select-deselect-jquery-tutorial-example.html" title="Multiple Checkbox Select/Deselect using jQuery &#8211; Tutorial with Example">Multiple Checkbox Select/Deselect using jQuery &#8211; Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2010/01/javascript-array-remove-element-js-array-delete-element.html" title="JavaScript Array Remove an Element ">JavaScript Array Remove an Element </a></li><li><a href="http://viralpatel.net/blogs/2009/11/disable-back-button-browser-javascript.html" title="Disable Back Button in Browser using JavaScript">Disable Back Button in Browser using JavaScript</a></li><li><a href="http://viralpatel.net/blogs/2009/10/create-search-engine-google-custom-search-api.html" title="Create your own Search Engine(Interface) using Google Custom Search API">Create your own Search Engine(Interface) using Google Custom Search API</a></li><li><a href="http://viralpatel.net/blogs/2009/09/default-text-label-textbox-javascript-jquery.html" title="Default Text Label in Textbox using JavaScript/jQuery">Default Text Label in Textbox using JavaScript/jQuery</a></li></ul></div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=mqE7NvUTFAg:P5G-vOG6iBY:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=mqE7NvUTFAg:P5G-vOG6iBY:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=mqE7NvUTFAg:P5G-vOG6iBY:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?i=mqE7NvUTFAg:P5G-vOG6iBY:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=mqE7NvUTFAg:P5G-vOG6iBY:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/viralpatelnet?a=mqE7NvUTFAg:P5G-vOG6iBY:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/viralpatelnet?d=I9og5sOYxJI" border="0"></img></a>
</div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2012/01/stopsopa-jquery-plugin.html/feed</wfw:commentRss> <slash:comments>6</slash:comments> <feedburner:origLink>http://viralpatel.net/blogs/2012/01/stopsopa-jquery-plugin.html</feedburner:origLink></item> </channel> </rss><!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: enhanced
Database Caching 40/114 queries in 0.076 seconds using disk: basic
Object Caching 1384/1505 objects using disk: basic

Served from: viralpatel.net @ 2012-05-16 21:05:28 -->

