<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	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/"
	>

<channel>
	<title>AndroidHive &#124; Tutorials, Games, Apps, Tips</title>
	<atom:link href="http://www.androidhive.info/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.androidhive.info</link>
	<description>Just another WordPress site</description>
	<lastBuildDate>Thu, 17 May 2012 06:50:41 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Android Combining Tab Layout and List View</title>
		<link>http://www.androidhive.info/2012/05/android-combining-tab-layout-and-list-view/</link>
		<comments>http://www.androidhive.info/2012/05/android-combining-tab-layout-and-list-view/#comments</comments>
		<pubDate>Sun, 13 May 2012 22:34:49 +0000</pubDate>
		<dc:creator>Ravi Tamada</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[List View]]></category>
		<category><![CDATA[Tab View]]></category>

		<guid isPermaLink="false">http://www.androidhive.info/?p=1547</guid>
		<description><![CDATA[In Android Tab Layout Tutorial i explained how to implement a tab view. This tutorial is about implementing list view inside a tab layout. Everything is same except tabs will have listview inside it. List data is displayed by fetching ...]]></description>
			<content:encoded><![CDATA[<p><br/>In <a href="http://www.androidhive.info/2011/08/android-tab-layout-tutorial/" class="ref-link">Android Tab Layout Tutorial</a> i explained how to implement a tab view. This tutorial is about implementing list view inside a tab layout. Everything is same except tabs will have listview inside it. List data is displayed by fetching json by making http request. I took an example of simple mailbox which will contains two list views for inbox, outbox messages and a profile tab.</p>
<div class="downloadsection"><a href="http://download.androidhive.info/download?code=ZwsVLsAvw0XfxUVnDkkQMzWGnscsMnGom7h7buQR2tnhQPKK5YB4QkMRKq%2FdsabKWSO4K2pPRuBvi3Rwi70Uw3s9OKcG94lJLreAYIVkgAUi3aQqRPC73ZQ7w%3D%3Dumu327kL6h5XqRPskBNHRSW4ckKjdPcpCSA" target="_blank"><img src="http://www.androidhive.info/wp-content/uploads/2011/08/download_btn.png" alt="Download Code" title="Download Code" width="173" height="41" class="alignnone size-full wp-image-423" /></a></div>
<div class="downloadsection">
<iframe width="590" height="330" src="http://www.youtube.com/embed/sSMQ149LuwA" frameborder="0" allowfullscreen></iframe>
</div>
<p>In this example i am displaying list view in each tab where the list data is fetched from a JSON.<br />
<br/><br />
Get Inbox JSON <a href="http://api.androidhive.info/mail/inbox.json" class="ref-link">here</a></p>
<pre class="brush: java; title: ; notranslate">
{
    &quot;messages&quot;: [
        {
                &quot;id&quot;: &quot;1&quot;,
                &quot;from&quot;: &quot;Android Hive&quot;,
                &quot;email&quot;: &quot;androidhive@gmail.com&quot;,
                &quot;subject&quot;: &quot;New Subscriber..&quot;,
                &quot;message&quot; : &quot;Tutorial about combing Android Tabview and ListView&quot;,
                &quot;date&quot;: &quot;May 9&quot;
        },
		{
                &quot;id&quot;: &quot;2&quot;,
                &quot;from&quot;: &quot;Pay Pal&quot;,
                &quot;email&quot;: &quot;paypal@paypal.com&quot;,
                &quot;subject&quot;: &quot;Payment Notification&quot;,
                &quot;message&quot; : &quot;Tutorial about combing Android Tabview and ListView&quot;,
                &quot;date&quot;: &quot;May 7&quot;
        },
        .
        .

    ]
}
</pre>
<p>Get Outbox JSON <a href="http://api.androidhive.info/mail/outbox.json" class="ref-link">here</a>.</p>
<pre class="brush: java; title: ; notranslate">
{
    &quot;messages&quot;: [
        {
                &quot;id&quot;: &quot;1&quot;,
                &quot;to&quot;: &quot;dine@gmail.com&quot;,
                &quot;subject&quot;: &quot;Movie Tickets Confirmation..&quot;,
                &quot;message&quot; : &quot;Tutorial about combing Android Tabview and ListView&quot;,
                &quot;date&quot;: &quot;May 22&quot;
        },
		{
                &quot;id&quot;: &quot;2&quot;,
                &quot;to&quot;: &quot;william@gmail.com&quot;,
                &quot;subject&quot;: &quot;Project estimataion details&quot;,
                &quot;message&quot; : &quot;Tutorial about combing Android Tabview and ListView&quot;,
                &quot;date&quot;: &quot;May 21&quot;
        },
        .
        .
        .
    ]
}
</pre>
<p>And get Profile JSON <a href="http://api.androidhive.info/mail/profile.json" class="ref-link">here</a></p>
<pre class="brush: java; title: ; notranslate">
{
    &quot;profile&quot;: {
        &quot;id&quot;: &quot;1&quot;,
        &quot;name&quot;: &quot;Ravi Tamada&quot;,
        &quot;email&quot;: &quot;ravi8x@gmail.com&quot;,
        &quot;mobile&quot;: &quot;+91 0000000000&quot;,
        &quot;address&quot;: &quot;xxx - xxx -xxxxxx&quot;
    }
}
</pre>
<p><br/></p>
<h3>Create new Project</h3>
<p>So let&#8217;s start with creation of new project in Eclipse IDE.</p>
<p class="sub-content"><strong>1</strong>. Create a new project <strong>File -> New -> Android Project</strong> and fill out required details.<br />
<strong>2</strong>. Open your Main Activity and extend the class from <em>TabActivity</em>.
</p>
<pre class="brush: java; title: ; notranslate">
public class AndroidTabAndListView extends TabActivity {
</pre>
<p class="sub-content">
<strong>3</strong>. Now open your <strong>main.xml</strong> under <strong>res -> layout</strong> folder and type the following code to create a tabview.
</p>
<pre class="brush: xml; title: main.xml; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;TabHost xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:id=&quot;@android:id/tabhost&quot;
    android:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot;&gt;
    &lt;LinearLayout
        android:orientation=&quot;vertical&quot;
        android:layout_width=&quot;fill_parent&quot;
        android:layout_height=&quot;fill_parent&quot;&gt;
        &lt;TabWidget
            android:id=&quot;@android:id/tabs&quot;
            android:layout_width=&quot;fill_parent&quot;
            android:layout_height=&quot;wrap_content&quot; /&gt;
        &lt;FrameLayout
            android:id=&quot;@android:id/tabcontent&quot;
            android:layout_width=&quot;fill_parent&quot;
            android:layout_height=&quot;fill_parent&quot;/&gt;
    &lt;/LinearLayout&gt;
&lt;/TabHost&gt;
</pre>
<p class="sub-content">
<strong>4</strong>. Create three activities for 3 tabs. I am creating 3 activities as <strong>InboxActivity.java</strong>, <strong>OutboxActvity.java</strong> and <strong>ProfileActivity.java</strong> and extend the classes from <em>ListActivity</em>.</p>
<pre class="brush: java; title: InboxActivity.java; notranslate">
package com.example.androidhive;

import android.app.ListActivity;
import android.os.Bundle;

public class InboxActivity extends ListActivity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.inbox_list);
    }
}
</pre>
<pre class="brush: java; title: OutboxActivity.java; notranslate">
package com.example.androidhive;

import android.app.ListActivity;
import android.os.Bundle;

public class OutboxActivity extends ListActivity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.outbox_list);
    }
}
</pre>
<p>Note that ProfileActivity.java in not ListActivity.</p>
<pre class="brush: java; title: ProfileActivity.java; notranslate">
package com.example.androidhive;

import android.app.Activity;
import android.os.Bundle;

public class ProfileActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.profile);
    }
}
</pre>
<p class="sub-content">
<strong>5</strong>. Now create xml layouts for the list views. Here we have two list views and a normal layout. So create totally 5 xml layouts. <strong>inbox_list.xml</strong>, <strong>outbox_list.xml</strong>, <strong>profile.xml</strong>, <strong>inbox_list_item.xml</strong> (inbox listview single row item), <strong>outbox_list_item.xml</strong> (outbox listview single row item)</p>
<p><strong>inbox_list.xml</strong></p>
<pre class="brush: xml; title: inbox_list.xml; 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:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot;
    android:orientation=&quot;vertical&quot; &gt;

    &lt;ListView
        android:id=&quot;@android:id/list&quot;
        android:layout_width=&quot;fill_parent&quot;
        android:layout_height=&quot;wrap_content&quot; /&gt;

&lt;/LinearLayout&gt;
</pre>
<p><strong>inbox_list_item.xml</strong></p>
<pre class="brush: xml; title: inbox_list_item.xml; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;wrap_content&quot;
    android:orientation=&quot;vertical&quot; &gt;

    &lt;!-- From Label --&gt;
    &lt;TextView
        android:id=&quot;@+id/from&quot;
        android:layout_width=&quot;fill_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:paddingTop=&quot;8dip&quot;
        android:paddingLeft=&quot;8dip&quot;
        android:paddingBottom=&quot;4dip&quot;
        android:textSize=&quot;20dip&quot;
        android:textStyle=&quot;bold&quot; /&gt;

    &lt;!-- Mail Subject --&gt;
    &lt;TextView android:id=&quot;@+id/subject&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:paddingLeft=&quot;8dip&quot;
        android:paddingBottom=&quot;6dip&quot;
        android:textSize=&quot;15dip&quot;
        android:layout_below=&quot;@id/from&quot;/&gt;

    &lt;!-- Mail date --&gt;
    &lt;TextView android:id=&quot;@+id/date&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_alignParentRight=&quot;true&quot;
        android:padding=&quot;8dip&quot;/&gt;/

&lt;/RelativeLayout&gt;
</pre>
<p><strong>outbox_list.xml</strong></p>
<pre class="brush: xml; title: outbox_list.xml; 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:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot;
    android:orientation=&quot;vertical&quot; &gt;

    &lt;ListView
        android:id=&quot;@android:id/list&quot;
        android:layout_width=&quot;fill_parent&quot;
        android:layout_height=&quot;wrap_content&quot; /&gt;

&lt;/LinearLayout&gt;
</pre>
<p><strong>outbox_list_item.xml</strong></p>
<pre class="brush: xml; title: outbox_list_item.xml; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;wrap_content&quot;
    android:orientation=&quot;vertical&quot; &gt;

    &lt;!-- Subject Label --&gt;
    &lt;TextView
        android:id=&quot;@+id/subject&quot;
        android:layout_width=&quot;fill_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:paddingTop=&quot;8dip&quot;
        android:paddingLeft=&quot;8dip&quot;
        android:paddingBottom=&quot;4dip&quot;
        android:textSize=&quot;18dip&quot;
        android:textStyle=&quot;bold&quot; /&gt;

    &lt;!-- To email --&gt;
    &lt;TextView android:id=&quot;@+id/to&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:paddingLeft=&quot;8dip&quot;
        android:paddingBottom=&quot;6dip&quot;
        android:textSize=&quot;15dip&quot;
        android:layout_below=&quot;@id/subject&quot;/&gt;

    &lt;!-- Mail date --&gt;
    &lt;TextView android:id=&quot;@+id/date&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_alignParentRight=&quot;true&quot;
        android:padding=&quot;8dip&quot;/&gt;

&lt;/RelativeLayout&gt;
</pre>
<p><strong>profile.xml</strong></p>
<pre class="brush: xml; title: profile.xml; 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:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot;
    android:orientation=&quot;vertical&quot;&gt;

    &lt;!-- Name --&gt;
    &lt;TextView android:id=&quot;@+id/name&quot;
        android:layout_width=&quot;fill_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:textSize=&quot;28dip&quot;
        android:paddingLeft=&quot;15dip&quot;
        android:layout_marginTop=&quot;15dip&quot;/&gt;

    &lt;TextView android:id=&quot;@+id/email&quot;
        android:layout_width=&quot;fill_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:textSize=&quot;20dip&quot;
        android:paddingLeft=&quot;15dip&quot;/&gt;

    &lt;TextView android:id=&quot;@+id/mobile&quot;
        android:layout_width=&quot;fill_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:textSize=&quot;21dip&quot;
        android:paddingLeft=&quot;15dip&quot;/&gt;

    &lt;TextView android:id=&quot;@+id/address&quot;
        android:layout_width=&quot;fill_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:textSize=&quot;20dip&quot;
        android:paddingLeft=&quot;15dip&quot;/&gt;

&lt;/LinearLayout&gt;
</pre>
<p class="sub-content">
<strong>6</strong>. Each and every tab needs an icon so design icons for each tab. We need three dimensions of each icon. Design each icon in <em>48 x 48 px</em>, <em>32 x 32 px</em> and <em>24 x 24 px</em> and place them in <em>drawable-hdpi</em>, <em>drawable-mdpi</em> and <em>drawable-ldpi</em> respectively. See following diagram for your guidance </p>
<div class="article-post-image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/tablayout_icon_sizes.png" alt="android tab layout icon sizes" title="android tab layout icon sizes" width="580" height="493" class="alignnone size-full wp-image-1605" />
</div>
<p class="sub-content">
<strong>7</strong>. Android icon states will be define in xml files with default and hover state configurations. For three icons we need the icon state configuration files. So create three 3 xml files under drawable-hdpi directory. Type the following code for icon states.</p>
<pre class="brush: xml; title: icon_inbox.xml; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;selector xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;
    &lt;!-- When selected, use grey --&gt;
    &lt;item android:drawable=&quot;@drawable/inbox_gray&quot;
          android:state_selected=&quot;true&quot; /&gt;
    &lt;!-- When not selected, use white--&gt;
    &lt;item android:drawable=&quot;@drawable/inbox_white&quot; /&gt;
&lt;/selector&gt;
</pre>
<pre class="brush: xml; title: icon_outbox.xml; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;selector xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;
    &lt;!-- When selected, use grey --&gt;
    &lt;item android:drawable=&quot;@drawable/outbox_gray&quot;
          android:state_selected=&quot;true&quot; /&gt;
    &lt;!-- When not selected, use white--&gt;
    &lt;item android:drawable=&quot;@drawable/outbox_white&quot; /&gt;
&lt;/selector&gt;
</pre>
<pre class="brush: xml; title: icon_profile.xml; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;selector xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;
    &lt;!-- When selected, use grey --&gt;
    &lt;item android:drawable=&quot;@drawable/profile_gray&quot;
          android:state_selected=&quot;true&quot; /&gt;
    &lt;!-- When not selected, use white--&gt;
    &lt;item android:drawable=&quot;@drawable/profile_white&quot; /&gt;
&lt;/selector&gt;
</pre>
<p class="sub-content">
<strong>8</strong>. Now open <strong>AndroidTabAndListView.java</strong> which is Main Activity and type the following code. In the following code we are creating three <em>TabSepcs</em> and adding them to <em>TabHost</em>.</p>
<pre class="brush: java; title: AndroidTabAndListView.java; notranslate">
package com.example.androidhive;

import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;

public class AndroidTabAndListView extends TabActivity {
	// TabSpec Names
	private static final String INBOX_SPEC = &quot;Inbox&quot;;
	private static final String OUTBOX_SPEC = &quot;Outbox&quot;;
	private static final String PROFILE_SPEC = &quot;Profile&quot;;

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

        TabHost tabHost = getTabHost();

        // Inbox Tab
        TabSpec inboxSpec = tabHost.newTabSpec(INBOX_SPEC);
        // Tab Icon
        inboxSpec.setIndicator(INBOX_SPEC, getResources().getDrawable(R.drawable.icon_inbox));
        Intent inboxIntent = new Intent(this, InboxActivity.class);
        // Tab Content
        inboxSpec.setContent(inboxIntent);

        // Outbox Tab
        TabSpec outboxSpec = tabHost.newTabSpec(OUTBOX_SPEC);
        outboxSpec.setIndicator(OUTBOX_SPEC, getResources().getDrawable(R.drawable.icon_outbox));
        Intent outboxIntent = new Intent(this, OutboxActivity.class);
        outboxSpec.setContent(outboxIntent);

        // Profile Tab
        TabSpec profileSpec = tabHost.newTabSpec(PROFILE_SPEC);
        profileSpec.setIndicator(PROFILE_SPEC, getResources().getDrawable(R.drawable.icon_profile));
        Intent profileIntent = new Intent(this, ProfileActivity.class);
        profileSpec.setContent(profileIntent);

        // Adding all TabSpec to TabHost
        tabHost.addTab(inboxSpec); // Adding Inbox tab
        tabHost.addTab(outboxSpec); // Adding Outbox tab
        tabHost.addTab(profileSpec); // Adding Profile tab
    }
}
</pre>
<p class="sub-content">
<strong>9</strong>. Now open your project make sure that you an entry of new activity name in <strong>AndroidManifest.xml</strong> file. Open you AndroidManifest.xml file and modify the code as below. Also don&#8217;t forgot to add INTERNET Permissions as we are getting JSON by making http request.
</p>
<pre class="brush: xml; title: AndroidManifest.xml; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    package=&quot;com.example.androidhive&quot;
    android:versionCode=&quot;1&quot;
    android:versionName=&quot;1.0&quot; &gt;

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

    &lt;application
        android:icon=&quot;@drawable/ic_launcher&quot;
        android:label=&quot;@string/app_name&quot; &gt;
        &lt;activity
            android:configChanges=&quot;keyboardHidden|orientation&quot;
            android:name=&quot;.AndroidTabAndListView&quot;
            android:label=&quot;@string/app_name&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;!-- Inbox Activity --&gt;
        &lt;activity android:name=&quot;.InboxActivity&quot; /&gt;

        &lt;!-- Outbox Activity --&gt;
        &lt;activity android:name=&quot;.OutboxActivity&quot; /&gt;

        &lt;!-- Profile Activity --&gt;
        &lt;activity android:name=&quot;.ProfileActivity&quot; /&gt;
    &lt;/application&gt;

    &lt;!-- Internet Permissions --&gt;
    &lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;

&lt;/manifest&gt;
</pre>
<p class="sub-content">
<strong>10</strong>. If you run your project now you will see tabs running without listviews. So all we need to do is implement listview in each tab activity. So open you individual tab activity classes and try to implement listview. If you are new to ListView i suggest you to go through <a href="http://www.androidhive.info/2011/10/android-listview-tutorial/" class="ref-link">Android ListView Tutorial</a> once.
</p>
<p><strong>InboxActivity.java</strong></p>
<pre class="brush: java; title: InboxActivity.java; notranslate">
package com.example.androidhive;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;

public class InboxActivity extends ListActivity {
	// Progress Dialog
	private ProgressDialog pDialog;

	// Creating JSON Parser object
	JSONParser jsonParser = new JSONParser();

	ArrayList&lt;HashMap&lt;String, String&gt;&gt; inboxList;

	// products JSONArray
	JSONArray inbox = null;

	// Inbox JSON url
	private static final String INBOX_URL = &quot;http://api.androidhive.info/mail/inbox.json&quot;;

	// ALL JSON node names
	private static final String TAG_MESSAGES = &quot;messages&quot;;
	private static final String TAG_ID = &quot;id&quot;;
	private static final String TAG_FROM = &quot;from&quot;;
	private static final String TAG_EMAIL = &quot;email&quot;;
	private static final String TAG_SUBJECT = &quot;subject&quot;;
	private static final String TAG_DATE = &quot;date&quot;;

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

		// Hashmap for ListView
        inboxList = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;();

        // Loading INBOX in Background Thread
        new LoadInbox().execute();
	}

	/**
	 * Background Async Task to Load all INBOX messages by making HTTP Request
	 * */
	class LoadInbox extends AsyncTask&lt;String, String, String&gt; {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(InboxActivity.this);
			pDialog.setMessage(&quot;Loading Inbox ...&quot;);
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		/**
		 * getting Inbox JSON
		 * */
		protected String doInBackground(String... args) {
			// Building Parameters
			List&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;();

			// getting JSON string from URL
			JSONObject json = jsonParser.makeHttpRequest(INBOX_URL, &quot;GET&quot;,
					params);

			// Check your log cat for JSON reponse
			Log.d(&quot;Inbox JSON: &quot;, json.toString());

			try {
				inbox = json.getJSONArray(TAG_MESSAGES);
				// looping through All messages
				for (int i = 0; i &lt; inbox.length(); i++) {
					JSONObject c = inbox.getJSONObject(i);

					// Storing each json item in variable
					String id = c.getString(TAG_ID);
					String from = c.getString(TAG_FROM);
					String subject = c.getString(TAG_SUBJECT);
					String date = c.getString(TAG_DATE);

					// creating new HashMap
					HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();

					// adding each child node to HashMap key =&gt; value
					map.put(TAG_ID, id);
					map.put(TAG_FROM, from);
					map.put(TAG_SUBJECT, subject);
					map.put(TAG_DATE, date);

					// adding HashList to ArrayList
					inboxList.add(map);
				}

			} catch (JSONException e) {
				e.printStackTrace();
			}

			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {
					/**
					 * Updating parsed JSON data into ListView
					 * */
					ListAdapter adapter = new SimpleAdapter(
							InboxActivity.this, inboxList,
							R.layout.inbox_list_item, new String[] { TAG_FROM, TAG_SUBJECT, TAG_DATE },
							new int[] { R.id.from, R.id.subject, R.id.date });
					// updating listview
					setListAdapter(adapter);
				}
			});

		}

	}
}
</pre>
<p><strong>OutboxActivity.java</strong></p>
<pre class="brush: java; title: InboxActivity.java; notranslate">
package com.example.androidhive;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;

public class OutboxActivity extends ListActivity {
	// Progress Dialog
	private ProgressDialog pDialog;

	// Creating JSON Parser object
	JSONParser jsonParser = new JSONParser();

	ArrayList&lt;HashMap&lt;String, String&gt;&gt; outboxList;

	// products JSONArray
	JSONArray outbox = null;

	// Outbox JSON url
	private static final String OUTBOX_URL = &quot;http://api.androidhive.info/mail/outbox.json&quot;;

	// ALL JSON node names
	private static final String TAG_MESSAGES = &quot;messages&quot;;
	private static final String TAG_ID = &quot;id&quot;;
	private static final String TAG_TO = &quot;to&quot;;
	private static final String TAG_SUBJECT = &quot;subject&quot;;
	private static final String TAG_DATE = &quot;date&quot;;

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

		// Hashmap for ListView
        outboxList = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;();

        // Loading OUTBOX in Background Thread
        new LoadOutbox().execute();
	}

	/**
	 * Background Async Task to Load all OUTBOX messages by making HTTP Request
	 * */
	class LoadOutbox extends AsyncTask&lt;String, String, String&gt; {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(OutboxActivity.this);
			pDialog.setMessage(&quot;Loading Outbox ...&quot;);
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		/**
		 * getting Outbox JSON
		 * */
		protected String doInBackground(String... args) {
			// Building Parameters
			List&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;();

			// getting JSON string from URL
			JSONObject json = jsonParser.makeHttpRequest(OUTBOX_URL, &quot;GET&quot;,
					params);

			// Check your log cat for JSON reponse
			Log.d(&quot;Outbox JSON: &quot;, json.toString());

			try {
				outbox = json.getJSONArray(TAG_MESSAGES);
				// looping through All messages
				for (int i = 0; i &lt; outbox.length(); i++) {
					JSONObject c = outbox.getJSONObject(i);

					// Storing each json item in variable
					String id = c.getString(TAG_ID);
					String to = c.getString(TAG_TO);
					String subject = c.getString(TAG_SUBJECT);
					String date = c.getString(TAG_DATE);

					// subject taking only first 23 chars
					// to fit into screen
					if(subject.length() &gt; 23){
						subject = subject.substring(0, 22) + &quot;..&quot;;
					}

					// creating new HashMap
					HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();

					// adding each child node to HashMap key =&gt; value
					map.put(TAG_ID, id);
					map.put(TAG_TO, to);
					map.put(TAG_SUBJECT, subject);
					map.put(TAG_DATE, date);

					// adding HashList to ArrayList
					outboxList.add(map);
				}

			} catch (JSONException e) {
				e.printStackTrace();
			}

			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {
					/**
					 * Updating parsed JSON data into ListView
					 * */
					ListAdapter adapter = new SimpleAdapter(
							OutboxActivity.this, outboxList,
							R.layout.outbox_list_item, new String[] { TAG_SUBJECT, TAG_TO, TAG_DATE },
							new int[] { R.id.subject, R.id.to, R.id.date });
					// updating listview
					setListAdapter(adapter);
				}
			});

		}

	}
}
</pre>
<p><strong>ProfileActivity.java</strong></p>
<pre class="brush: java; title: ProfileActivity.java; notranslate">
package com.example.androidhive;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class ProfileActivity extends Activity {
	// All xml labels
	TextView txtName;
	TextView txtEmail;
	TextView txtMobile;
	TextView txtAddress;

	// Progress Dialog
	private ProgressDialog pDialog;

	// Creating JSON Parser object
	JSONParser jsonParser = new JSONParser();

	// Profile json object
	JSONObject profile;

	// Profile JSON url
	private static final String PROFILE_URL = &quot;http://api.androidhive.info/mail/profile.json&quot;;

	// ALL JSON node names
	private static final String TAG_PROFILE = &quot;profile&quot;;
	private static final String TAG_ID = &quot;id&quot;;
	private static final String TAG_NAME = &quot;name&quot;;
	private static final String TAG_EMAIL = &quot;email&quot;;
	private static final String TAG_MOBILE = &quot;mobile&quot;;
	private static final String TAG_ADDRESS = &quot;address&quot;;

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

		txtName = (TextView) findViewById(R.id.name);
		txtEmail = (TextView) findViewById(R.id.email);
		txtMobile = (TextView) findViewById(R.id.mobile);
		txtAddress = (TextView) findViewById(R.id.address);

        // Loading Profile in Background Thread
        new LoadProfile().execute();
	}

	/**
	 * Background Async Task to Load profile by making HTTP Request
	 * */
	class LoadProfile extends AsyncTask&lt;String, String, String&gt; {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(ProfileActivity.this);
			pDialog.setMessage(&quot;Loading profile ...&quot;);
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		/**
		 * getting Profile JSON
		 * */
		protected String doInBackground(String... args) {
			// Building Parameters
			List&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;();

			// getting JSON string from URL
			JSONObject json = jsonParser.makeHttpRequest(PROFILE_URL, &quot;GET&quot;,
					params);

			// Check your log cat for JSON reponse
			Log.d(&quot;Profile JSON: &quot;, json.toString());

			try {
				// profile json object
				profile = json.getJSONObject(TAG_PROFILE);
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {
					/**
					 * Updating parsed JSON data into ListView
					 * */
					// Storing each json item in variable
					try {
						String id = profile.getString(TAG_ID);
						String name = profile.getString(TAG_NAME);
						String email = profile.getString(TAG_EMAIL);
						String mobile = profile.getString(TAG_MOBILE);
						String address = profile.getString(TAG_ADDRESS);

						// displaying all data in textview
						txtName.setText(name);
						txtEmail.setText(&quot;Email: &quot; + email);
						txtMobile.setText(&quot;Mobile: &quot; + mobile);
						txtAddress.setText(&quot;Add: &quot; + address);

					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
			});

		}

	}
}
</pre>
<p><strong>11</strong>. Finally create a class called <strong>JSONParser.java</strong> and paste the following code as we need a parser class to parse the json.</p>
<pre class="brush: java; title: JSONParser.java; notranslate">
package com.example.androidhive;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = &quot;&quot;;

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List&lt;NameValuePair&gt; params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == &quot;POST&quot;){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == &quot;GET&quot;){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, &quot;utf-8&quot;);
                url += &quot;?&quot; + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }            

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, &quot;iso-8859-1&quot;), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + &quot;\n&quot;);
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e(&quot;Buffer Error&quot;, &quot;Error converting result &quot; + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e(&quot;JSON Parser&quot;, &quot;Error parsing data &quot; + e.toString());
        }

        // return JSON String
        return jObj;

    }
}
</pre>
<p><strong>12</strong>. Now Run &#038; Test your project.</p>
<div class="image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/tab_listview_inbox.png" alt="android tab layout and list view" title="android tab layout and list view" width="580" height="628" class="alignnone size-full wp-image-1612" />
</div>
<div class="image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/tab_listview_outbox.png" alt="android tab layout and list view" title="android tab layout and list view" width="580" height="628" class="alignnone size-full wp-image-1612" />
</div>
<div class="image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/tab_listview_profile.png" alt="android tab layout and list view" title="android tab layout and list view" width="580" height="628" class="alignnone size-full wp-image-1612" />
</div>
<div style="display:none">
This image is for thumbnail purpose<br />
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/banner_tablayout_listview.png" alt="android combining tab layout and list view" title="android combining tab layout and list view" width="166" height="198" class="alignnone size-full wp-image-1616" />
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.androidhive.info/2012/05/android-combining-tab-layout-and-list-view/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to connect Android with PHP, MySQL</title>
		<link>http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/</link>
		<comments>http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/#comments</comments>
		<pubDate>Wed, 02 May 2012 13:25:38 +0000</pubDate>
		<dc:creator>Ravi Tamada</dc:creator>
				<category><![CDATA[Async]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[List View]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[UI]]></category>

		<guid isPermaLink="false">http://www.androidhive.info/?p=1397</guid>
		<description><![CDATA[We are going see how to make a very simple Android app (in our case, a product inventory app) that will call a PHP script to perform basic CRUD(Create, Read, Update, Delete) operations. To brief you on the architecture, this ...]]></description>
			<content:encoded><![CDATA[<p>We are going see how to make a very simple Android app (in our case, a product inventory app) that will call a PHP script to perform basic CRUD(Create, Read, Update, Delete) operations. To brief you on the architecture, this is how it works. First your android app calls a PHP script in order to perform a data operation, lets say “create”. The PHP script then connects to your MySQL database to perform the operation.<br />
So the data flows from your Android app to PHP script then finally is stored in your MySQL database. Allright, lets dig deeper.</p>
<div class="downloadsection"><a href="http://download.androidhive.info/download?code=oIFSaPXi6sxpDiCAwRnSRyAex70W8TTQCmRqwerfdsja1cbcpV40Hj5qQmwMKYdOatnuTJv9IZS0hxcZHagQQ1P2Fa8cyYwCRWjAcJYZUTfAsMlOk9" target="_blank"><img class="alignnone size-full wp-image-423" title="Download Code" src="http://www.androidhive.info/wp-content/uploads/2011/08/download_btn.png" alt="Download Code" width="173" height="41"></a></div>
<div class="downloadsection">
<iframe width="590" height="330" src="http://www.youtube.com/embed/D86beKXvjd0" frameborder="0" allowfullscreen></iframe>
</div>
<p></p>
<div class="warning">
Please note that the purpose of the code that I have provided here is to, ease you (beginner level) into connecting an Android app with PHP, MYSQL. You should not take this as a standard or secure coding practice. In production environment, you ideally need to avoid any code that will potentially inject vulnerabilities (like MYSQL Injection). MySQL injection itself is a huge topic and cannot be covered in this single post and that is not the agenda of this post either.
</div>
<p></p>
<h3>1. What is WAMP Server</h3>
<p>WAMP is acronym for Windows, Apache, MySQL and PHP, Perl, Python. WAMP software is one click installer which creates an environment for developing PHP, MySQL web application. By installing this software you will be installing <strong>Apache</strong>, <strong>MySQL</strong> and <strong>PHP</strong>. Alternatively you can use <a href="http://www.apachefriends.org/en/xampp-windows.html" class="ref-link" target="_blank">XAMP</a> Server also.</p>
<div class="image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/wamp_server.png" alt="wamp server installation" title="wamp server installation" width="580" height="146" class="alignnone size-full wp-image-1523" />
</div>
<p></p>
<h3>2. Installing and Running WAMP Server</h3>
<p>Download &amp; Install WAMP server from <a href="http://wampserver.com/en/" class="ref-link" target="_blank">www.wampserver.com/en/</a>. Once you have installed wamp server, launch the program from Start -&gt; All Programs -&gt; WampServer -&gt; StartWampServer.</p>
<p>You can test your server by opening the address <a href="http://localhost/" class="ref-link" target="_blank">http://localhost/</a> in your browser.<br />
Also you can check phpmyadmin by opening <a href="http://localhost/phpmyadmin" class="ref-link" target="_blank">http://localhost/phpmyadmin</a></p>
<p>Following is a screen cast of Downloading and Installing WAMP Server.</p>
<div class="downloadsection">
<iframe width="560" height="315" src="http://www.youtube.com/embed/a-dcmT-xGHc" frameborder="0" allowfullscreen></iframe>
</div>
<p></p>
<h3>3. Creating and Running PHP Project</h3>
<p>Now you have the environment ready to develop a PHP &amp; MySQL project. Go to the location where you installed WAMP server (In my case i installed in <strong>C:\wamp\</strong>) and go to <strong>www</strong> folder and create a new folder for your project. You have to place all your project files inside this folder.</p>
<p>Create a folder called <strong>android_connect</strong> and create a new php file called <strong>test.php</strong> and try out simple php code. After placing following code try to open <a href="http://localhost/android_connect/test.php" class="ref-link" target="_blank">http://localhost/android_connect/test.php</a> and you should see a message called “<strong>Welcome, I am connecting Android to PHP, MySQL</strong>“.</p>
<p><strong>test.php</strong></p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
    echo &quot;Welcome, I am connecting Android to PHP, MySQL&quot;;
?&gt;
</pre>
<p>Following is a screen cast of Creating and Running a simple PHP project.</p>
<div class="downloadsection">
<iframe width="560" height="315" src="http://www.youtube.com/embed/M9m93bD9CK4" frameborder="0" allowfullscreen></iframe>
</div>
<p></p>
<h3>4. Creating MySQL Database and Tables</h3>
<p>In this tutorial i am creating a simple database with one table. Through out this tutorial i am using same table to perform example operations. Now open <strong>phpmyadmin</strong> by opening the address <a href="http://localhost/phpmyadmin" class="ref-link" target="_blank">http://localhost/phpmyadmin/</a> in your browser. You can use the PhpMyAdmin tool to create a database and a table.</p>
<p>I am creating a database named androidhive and a table called products.</p>
<pre class="brush: java; title: ; notranslate" title="">CREATE DATABASE androidhive;
</pre>
<pre class="brush: java; title: ; notranslate" title="">CREATE TABLE products(
pid int(11) primary key auto_increment,
name varchar(100) not null,
price decimal(10,2) not null,
description text,
created_at timestamp default now(),
updated_at timestamp
);
</pre>
<p>Following is a screen cast of Creating database and tables in phpmyadmin</p>
<div class="downloadsection">
<iframe width="560" height="315" src="http://www.youtube.com/embed/RLswUlMSMb4" frameborder="0" allowfullscreen></iframe>
</div>
<p></p>
<h3>5. Connecting to MySQL database using PHP</h3>
<p>Now the actual server side coding starts. Create a PHP class to connect to MySQL database. The main purpose of this class is to open a connection to database and close the connection whenever its not needed. So create two files called <strong>db_config.php</strong> and <strong>db_connect.php</strong></p>
<p><strong>db_config.php</strong> – will have database connection variables<br />
<strong>db_connect.php</strong> – a class file to connect to database</p>
<p>Following is code for two php files</p>
<p>
<strong>db_config.php</strong></p>
<pre class="brush: php; title: db_config.php; notranslate" title="db_config.php">&lt;?php

/*
 * All database connection variables
 */

define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "androidhive"); // database name
define('DB_SERVER', "localhost"); // db server
?&gt;
</pre>
<p><strong>db_connect.php</strong></p>
<pre class="brush: php; title: db_connect.php; notranslate" title="db_connect.php">&lt;?php

/**
 * A class file to connect to database
 */
class DB_CONNECT {

    // constructor
    function __construct() {
        // connecting to database
        $this-&gt;connect();
    }

    // destructor
    function __destruct() {
        // closing db connection
        $this-&gt;close();
    }

    /**
     * Function to connect with database
     */
    function connect() {
        // import database connection variables
        require_once __DIR__ . '/db_config.php';

        // Connecting to mysql database
        $con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());

        // Selecing database
        $db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());

        // returing connection cursor
        return $con;
    }

    /**
     * Function to close db connection
     */
    function close() {
        // closing db connection
        mysql_close();
    }

}

?&gt;
</pre>
<p><strong>Usage:</strong> When ever you want to connect to MySQL database and do some operations use the db_connect.php class like this</p>
<pre class="brush: php; title: ; notranslate" title="">$db = new DB_CONNECT(); // creating class object(will open database connection)
</pre>
<p></p>
<h3>6. Basic MySQL CRUD Operations using PHP</h3>
<p>In this tutorial i am covering basic <strong>CRUD (Create, Read, Update, Delete)</strong> operations on MySQL database using PHP.<br />
If you are a novice about PHP and MySQL i suggest, you to learn basic <a href="http://www.w3schools.com/php/php_intro.asp" class="ref-link" target="_blank">PHP</a> and <a class="ref-link" href="http://www.w3schools.com/sql/sql_syntax.asp" target="_blank">SQL</a> here.</p>
<h3>6.a) Creating a row in MySQL (Creating a new product row)</h3>
<p> In your PHP project create a new php file called <strong>create_product.php</strong> and place the following code. This file is mainly for creating a new product in products table.</p>
<p> In the following code i am reading product data via POST and storing them in products table. At the end i am echoing  appropriate JSON as response.</p>
<pre class="brush: php; title: create_product.php; notranslate" title="create_product.php">&lt;?php

/*
 * Following code will create a new product row
 * All product details are read from HTTP Post Request
 */

// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['name']) &amp;&amp; isset($_POST['price']) &amp;&amp; isset($_POST['description'])) {

    $name = $_POST['name'];
    $price = $_POST['price'];
    $description = $_POST['description'];

    // include db connect class
    require_once __DIR__ . '/db_connect.php';

    // connecting to db
    $db = new DB_CONNECT();

    // mysql inserting a new row
    $result = mysql_query("INSERT INTO products(name, price, description) VALUES('$name', '$price', '$description')");

    // check if row inserted or not
    if ($result) {
        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "Product successfully created.";

        // echoing JSON response
        echo json_encode($response);
    } else {
        // failed to insert row
        $response["success"] = 0;
        $response["message"] = "Oops! An error occurred.";

        // echoing JSON response
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

    // echoing JSON response
    echo json_encode($response);
}
?&gt;
</pre>
<p>For the above code JSON response will be like</p>
<p>When POST param(s) is missing</p>
<pre class="brush: java; title: ; notranslate">
{
    &quot;success&quot;: 0,
    &quot;message&quot;: &quot;Required field(s) is missing&quot;
}
</pre>
<p>When product is successfully created</p>
<pre class="brush: java; title: ; notranslate" title="">{
    "success": 1,
    "message": "Product successfully created."
}
</pre>
<p>When error occurred while inserting data</p>
<pre class="brush: java; title: ; notranslate" title="">{
    "success": 0,
    "message": "Oops! An error occurred."
}
</pre>
<p></p>
<h3>6.b) Reading a Row from MySQL (Reading product details)</h3>
<p>Create a new php file called get_product_details.php and write the following code. This file will get single product details by taking product id (pid) as post parameter.</p>
<pre class="brush: php; title: get_product_details.php; notranslate" title="get_product_details.php">&lt;?php

/*
 * Following code will get single product details
 * A product is identified by product id (pid)
 */

// array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// check for post data
if (isset($_GET["pid"])) {
    $pid = $_GET['pid'];

    // get a product from products table
    $result = mysql_query("SELECT *FROM products WHERE pid = $pid");

    if (!empty($result)) {
        // check for empty result
        if (mysql_num_rows($result) &gt; 0) {

            $result = mysql_fetch_array($result);

            $product = array();
            $product["pid"] = $result["pid"];
            $product["name"] = $result["name"];
            $product["price"] = $result["price"];
            $product["description"] = $result["description"];
            $product["created_at"] = $result["created_at"];
            $product["updated_at"] = $result["updated_at"];
            // success
            $response["success"] = 1;

            // user node
            $response["product"] = array();

            array_push($response["product"], $product);

            // echoing JSON response
            echo json_encode($response);
        } else {
            // no product found
            $response["success"] = 0;
            $response["message"] = "No product found";

            // echo no users JSON
            echo json_encode($response);
        }
    } else {
        // no product found
        $response["success"] = 0;
        $response["message"] = "No product found";

        // echo no users JSON
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

    // echoing JSON response
    echo json_encode($response);
}
?&gt;
</pre>
<p>The json response for the above file will be</p>
<p>When successfully getting product details</p>
<pre class="brush: java; title: ; notranslate" title="">{
    "success": 1,
    "product": [
        {
            "pid": "1",
            "name": "iPHone 4S",
            "price": "300.00",
            "description": "iPhone 4S white",
            "created_at": "2012-04-29 01:41:42",
            "updated_at": "0000-00-00 00:00:00"
        }
    ]
}
</pre>
<p>When no product found with matched pid</p>
<pre class="brush: java; title: ; notranslate" title="">{
    "success": 0,
    "message": "No product found"
}
</pre>
<p></p>
<h3>6.c) Reading All Rows from MySQL (Reading all products)</h3>
<p>We need a json to list all the products on android device. So create a new php file named <strong>get_all_products.php</strong> and write following code.</p>
<pre class="brush: php; title: get_all_products.php; notranslate" title="get_all_products.php">&lt;?php

/*
 * Following code will list all the products
 */

// array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// get all products from products table
$result = mysql_query("SELECT *FROM products") or die(mysql_error());

// check for empty result
if (mysql_num_rows($result) &gt; 0) {
    // looping through all results
    // products node
    $response["products"] = array();

    while ($row = mysql_fetch_array($result)) {
        // temp user array
        $product = array();
        $product["pid"] = $row["pid"];
        $product["name"] = $row["name"];
        $product["price"] = $row["price"];
        $product["created_at"] = $row["created_at"];
        $product["updated_at"] = $row["updated_at"];

        // push single product into final response array
        array_push($response["products"], $product);
    }
    // success
    $response["success"] = 1;

    // echoing JSON response
    echo json_encode($response);
} else {
    // no products found
    $response["success"] = 0;
    $response["message"] = "No products found";

    // echo no users JSON
    echo json_encode($response);
}
?&gt;
</pre>
<p>And the JSON response for above code</p>
<p>Listing all Products</p>
<pre class="brush: java; title: ; notranslate" title="">{
    "products": [
        {
            "pid": "1",
            "name": "iPhone 4S",
            "price": "300.00",
            "created_at": "2012-04-29 02:04:02",
            "updated_at": "0000-00-00 00:00:00"
        },
        {
            "pid": "2",
            "name": "Macbook Pro",
            "price": "600.00",
            "created_at": "2012-04-29 02:04:51",
            "updated_at": "0000-00-00 00:00:00"
        },
        {
            "pid": "3",
            "name": "Macbook Air",
            "price": "800.00",
            "created_at": "2012-04-29 02:05:57",
            "updated_at": "0000-00-00 00:00:00"
        },
        {
            "pid": "4",
            "name": "OS X Lion",
            "price": "100.00",
            "created_at": "2012-04-29 02:07:14",
            "updated_at": "0000-00-00 00:00:00"
        }
    ],
    "success": 1
}
</pre>
<p>When products not found</p>
<pre class="brush: java; title: ; notranslate" title="">{
    "success": 0,
    "message": "No products found"
}
</pre>
<p></p>
<h3>6.d) Updating a Row in MySQL (Updating product details)</h3>
<p>Create a php file named <strong>update_product.php</strong> to update product details. Each product is identified by pid.</p>
<pre class="brush: php; title: update_product.php; notranslate" title="update_product.php">&lt;?php

/*
 * Following code will update a product information
 * A product is identified by product id (pid)
 */

// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['pid']) &amp;&amp; isset($_POST['name']) &amp;&amp; isset($_POST['price']) &amp;&amp; isset($_POST['description'])) {

    $pid = $_POST['pid'];
    $name = $_POST['name'];
    $price = $_POST['price'];
    $description = $_POST['description'];

    // include db connect class
    require_once __DIR__ . '/db_connect.php';

    // connecting to db
    $db = new DB_CONNECT();

    // mysql update row with matched pid
    $result = mysql_query("UPDATE products SET name = '$name', price = '$price', description = '$description' WHERE pid = $pid");

    // check if row inserted or not
    if ($result) {
        // successfully updated
        $response["success"] = 1;
        $response["message"] = "Product successfully updated.";

        // echoing JSON response
        echo json_encode($response);
    } else {

    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

    // echoing JSON response
    echo json_encode($response);
}
?&gt;
</pre>
<p>The json reponse of above code, when product is updated successfully</p>
<pre class="brush: java; title: ; notranslate" title="">{
    "success": 1,
    "message": "Product successfully updated."
}
</pre>
<p></p>
<h3>6.e) Deleting a Row in MySQL (Deleting a product)</h3>
<p>The last operation is deletion on database. Create a new php file called delete_product.php and paste the following code. The main functionality of this file is to delete a product from database.</p>
<pre class="brush: php; title: delete_product.php; notranslate" title="delete_product.php">&lt;?php

/*
 * Following code will delete a product from table
 * A product is identified by product id (pid)
 */

// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['pid'])) {
    $pid = $_POST['pid'];

    // include db connect class
    require_once __DIR__ . '/db_connect.php';

    // connecting to db
    $db = new DB_CONNECT();

    // mysql update row with matched pid
    $result = mysql_query("DELETE FROM products WHERE pid = $pid");

    // check if row deleted or not
    if (mysql_affected_rows() &gt; 0) {
        // successfully updated
        $response["success"] = 1;
        $response["message"] = "Product successfully deleted";

        // echoing JSON response
        echo json_encode($response);
    } else {
        // no product found
        $response["success"] = 0;
        $response["message"] = "No product found";

        // echo no users JSON
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

    // echoing JSON response
    echo json_encode($response);
}
?&gt;
</pre>
<p>When product successfully deleted</p>
<pre class="brush: java; title: ; notranslate" title="">{
    "success": 1,
    "message": "Product successfully deleted"
}
</pre>
<p>When product not found</p>
<pre class="brush: java; title: ; notranslate" title="">{
    "success": 0,
    "message": "No product found"
}
</pre>
<p>Until now, we built a simple api for our products table. We are now done with the server side coding (PHP) and its time to take a break and start our actual android application coding.</p>
<p></p>
<h3>7. Creating Android Application</h3>
<p>Create a new project in your Eclipse IDE  by filling the required details.</p>
<p><strong>1</strong>. Create new project in Eclipse IDE by going to <strong>File ⇒ New ⇒ Android Project</strong> and name the Activity class name as <strong>MainScreenActivity</strong>.</p>
<p><strong>2</strong>. Open your <strong>AndroidManifest.xml</strong> file and add following code. First i am adding all the classes i am creating to manifest file. Also i am adding INTERNET Connect permission.</p>
<pre class="brush: xml; title: AndroidManifest.xml; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    package=&quot;com.example.androidhive&quot;
    android:versionCode=&quot;1&quot;
    android:versionName=&quot;1.0&quot; &gt;

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

    &lt;application
        android:configChanges=&quot;keyboardHidden|orientation&quot;
        android:icon=&quot;@drawable/ic_launcher&quot;
        android:label=&quot;@string/app_name&quot; &gt;

        &lt;activity
            android:name=&quot;.MainScreenActivity&quot;
            android:label=&quot;@string/app_name&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;!-- All Product Activity --&gt;
        &lt;activity
            android:name=&quot;.AllProductsActivity&quot;
            android:label=&quot;All Products&quot; &gt;
        &lt;/activity&gt;

        &lt;!-- Add Product Activity --&gt;
        &lt;activity
            android:name=&quot;.NewProductActivity&quot;
            android:label=&quot;Add New Product&quot; &gt;
        &lt;/activity&gt;

        &lt;!-- Edit Product Activity --&gt;
        &lt;activity
            android:name=&quot;.EditProductActivity&quot;
            android:label=&quot;Edit Product&quot; &gt;
        &lt;/activity&gt;
    &lt;/application&gt;

    &lt;!--  Internet Permissions --&gt;
    &lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;

&lt;/manifest&gt;
</pre>
<p><strong>3</strong>. Now create a new xml file under <strong>res ⇒ layout</strong> folder and name it as <strong>main_screen.xml</strong> This  layout file contains two simple buttons to view all products and add a new product.</p>
<pre class="brush: xml; title: main_screen.xml; notranslate" title="main_screen.xml">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal"&gt;

    &lt;!--  Sample Dashboard screen with Two buttons --&gt;
    &lt;!--  Button to view all products screen --&gt;
    &lt;Button android:id="@+id/btnViewProducts"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="View Products"
        android:layout_marginTop="25dip"/&gt;

    &lt;!--  Button to create a new product screen --&gt;
    &lt;Button android:id="@+id/btnCreateProduct"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Add New Products"
        android:layout_marginTop="25dip"/&gt;

&lt;/LinearLayout&gt;
</pre>
<div class="image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/main_screen1.png" alt="main screen" title="main screen" width="580" height="628" class="alignnone size-full wp-image-1529" />
</div>
<p><strong>4</strong>. Open you main activity class which is <strong>MainScreenActivity.java</strong> and write click events for two button which are mentioned in <strong>main_screen.xml</strong> layout.</p>
<pre class="brush: java; title: MainScreenActivity.java; notranslate">
package com.example.androidhive;

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

public class MainScreenActivity extends Activity{

	Button btnViewProducts;
	Button btnNewProduct;

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

		// Buttons
		btnViewProducts = (Button) findViewById(R.id.btnViewProducts);
		btnNewProduct = (Button) findViewById(R.id.btnCreateProduct);

		// view products click event
		btnViewProducts.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				// Launching All products Activity
				Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
				startActivity(i);

			}
		});

		// view products click event
		btnNewProduct.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				// Launching create new product activity
				Intent i = new Intent(getApplicationContext(), NewProductActivity.class);
				startActivity(i);

			}
		});
	}
}
</pre>
<p></p>
<h3>Displaying All Products in ListView (Read)</h3>
<p><strong>5</strong>. Now we need an Activity display all the products in list view format. As we know list view needs two xml files, one for listview and other is for single list row. Create two xml files under <strong>res ⇒ layout</strong> folder and name it as <strong>all_products.xml</strong> and <strong>list_item.xml</strong></p>
<p><strong>all_products.xml</strong></p>
<pre class="brush: xml; title: all_products.xml; notranslate" title="all_products.xml">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"&gt;
	&lt;!-- Main ListView
		 Always give id value as list(@android:id/list)
	--&gt;
    &lt;ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/&gt;

&lt;/LinearLayout&gt;
</pre>
<p><strong>list_item.xml</strong></p>
<pre class="brush: xml; title: list_item.xml; notranslate" title="list_item.xml">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" &gt;

    &lt;!-- Product id (pid) - will be HIDDEN - used to pass to other activity --&gt;
    &lt;TextView
        android:id="@+id/pid"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:visibility="gone" /&gt;

    &lt;!-- Name Label --&gt;
    &lt;TextView
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingTop="6dip"
        android:paddingLeft="6dip"
        android:textSize="17dip"
        android:textStyle="bold" /&gt;

&lt;/LinearLayout&gt;
</pre>
<p><strong>6</strong>. Create a new class file and name it as <strong>AllProductsActivity.java</strong>. In the following code</p>
<p>-&gt; First a request is send to <strong>get_all_products.php</strong> file using a Background Async task thread.<br />
-&gt; After getting JSON from get_all_products.php, i parsed it and displayed in a listview.<br />
-&gt; If there are no products found <strong>AddNewProductAcivity</strong> is launched.</p>
<pre class="brush: java; title: AllProductsActivity.java; notranslate" title="AllProductsActivity.java">package com.example.androidhive;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class AllProductsActivity extends ListActivity {

	// Progress Dialog
	private ProgressDialog pDialog;

	// Creating JSON Parser object
	JSONParser jParser = new JSONParser();

	ArrayList&lt;HashMap&lt;String, String&gt;&gt; productsList;

	// url to get all products list
	private static String url_all_products = "http://api.androidhive.info/android_connect/get_all_products.php";

	// JSON Node names
	private static final String TAG_SUCCESS = "success";
	private static final String TAG_PRODUCTS = "products";
	private static final String TAG_PID = "pid";
	private static final String TAG_NAME = "name";

	// products JSONArray
	JSONArray products = null;

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

		// Hashmap for ListView
		productsList = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;();

		// Loading products in Background Thread
		new LoadAllProducts().execute();

		// Get listview
		ListView lv = getListView();

		// on seleting single product
		// launching Edit Product Screen
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView&lt;?&gt; parent, View view,
					int position, long id) {
				// getting values from selected ListItem
				String pid = ((TextView) view.findViewById(R.id.pid)).getText()
						.toString();

				// Starting new intent
				Intent in = new Intent(getApplicationContext(),
						EditProductActivity.class);
				// sending pid to next activity
				in.putExtra(TAG_PID, pid);

				// starting new activity and expecting some response back
				startActivityForResult(in, 100);
			}
		});

	}

	// Response from Edit Product Activity
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		// if result code 100
		if (resultCode == 100) {
			// if result code 100 is received
			// means user edited/deleted product
			// reload this screen again
			Intent intent = getIntent();
			finish();
			startActivity(intent);
		}

	}

	/**
	 * Background Async Task to Load all product by making HTTP Request
	 * */
	class LoadAllProducts extends AsyncTask&lt;String, String, String&gt; {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(AllProductsActivity.this);
			pDialog.setMessage("Loading products. Please wait...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		/**
		 * getting All products from url
		 * */
		protected String doInBackground(String... args) {
			// Building Parameters
			List&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;();
			// getting JSON string from URL
			JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

			// Check your log cat for JSON reponse
			Log.d("All Products: ", json.toString());

			try {
				// Checking for SUCCESS TAG
				int success = json.getInt(TAG_SUCCESS);

				if (success == 1) {
					// products found
					// Getting Array of Products
					products = json.getJSONArray(TAG_PRODUCTS);

					// looping through All Products
					for (int i = 0; i &lt; products.length(); i++) {
						JSONObject c = products.getJSONObject(i);

						// Storing each json item in variable
						String id = c.getString(TAG_PID);
						String name = c.getString(TAG_NAME);

						// creating new HashMap
						HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();

						// adding each child node to HashMap key =&gt; value
						map.put(TAG_PID, id);
						map.put(TAG_NAME, name);

						// adding HashList to ArrayList
						productsList.add(map);
					}
				} else {
					// no products found
					// Launch Add New product Activity
					Intent i = new Intent(getApplicationContext(),
							NewProductActivity.class);
					// Closing all previous activities
					i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(i);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {
					/**
					 * Updating parsed JSON data into ListView
					 * */
					ListAdapter adapter = new SimpleAdapter(
							AllProductsActivity.this, productsList,
							R.layout.list_item, new String[] { TAG_PID,
									TAG_NAME},
							new int[] { R.id.pid, R.id.name });
					// updating listview
					setListAdapter(adapter);
				}
			});

		}

	}
}
</pre>
<div class="image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/all_products1.png" alt="android list products" title="android list products" width="580" height="628" class="alignnone size-full wp-image-1530" />
</div>
<p></p>
<h3>Adding a New Product (Write)</h3>
<p><strong>7</strong>. Create a new view and acivity to add a new product into mysql database. Create a simple form which contains EditText for product name, price and description.</p>
<p>Create a new xml file and name it as <strong>add_product.xml</strong> and paste the following code to create a simple form.</p>
<p><strong>add_product.xml</strong></p>
<pre class="brush: xml; title: add_product.xml; notranslate" title="add_product.xml">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" &gt;

    &lt;!-- Name Label --&gt;
    &lt;TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Product Name"
        android:paddingLeft="10dip"
        android:paddingRight="10dip"
        android:paddingTop="10dip"
        android:textSize="17dip"/&gt;

    &lt;!-- Input Name --&gt;
	&lt;EditText android:id="@+id/inputName"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:layout_margin="5dip"
	    android:layout_marginBottom="15dip"
	    android:singleLine="true"/&gt;

	&lt;!-- Price Label --&gt;
    &lt;TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Price"
        android:paddingLeft="10dip"
        android:paddingRight="10dip"
        android:paddingTop="10dip"
        android:textSize="17dip"/&gt;

    &lt;!-- Input Price --&gt;
	&lt;EditText android:id="@+id/inputPrice"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:layout_margin="5dip"
	    android:layout_marginBottom="15dip"
	    android:singleLine="true"
	    android:inputType="numberDecimal"/&gt;

	&lt;!-- Description Label --&gt;
    &lt;TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Description"
        android:paddingLeft="10dip"
        android:paddingRight="10dip"
        android:paddingTop="10dip"
        android:textSize="17dip"/&gt;

    &lt;!-- Input description --&gt;
	&lt;EditText android:id="@+id/inputDesc"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:layout_margin="5dip"
	    android:layout_marginBottom="15dip"
	    android:lines="4"
	    android:gravity="top"/&gt;

	&lt;!-- Button Create Product --&gt;
	&lt;Button android:id="@+id/btnCreateProduct"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="Create Product"/&gt;

&lt;/LinearLayout&gt;
</pre>
<div class="image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/add_new_product1.png" alt="android adding new product" title="android adding new product" width="580" height="628" class="alignnone size-full wp-image-1531" />
</div>
<p><strong>8</strong>. Now create new Activity to insert a new product into mysql database. Create a class file and name it as <strong>NewProductActivity.java</strong> and type the following code. In the following code</p>
<p>-&gt; First new product data is read from the EditText form and formatted into a basic params.<br />
-&gt; A request is made to <strong>create_product.php</strong> to create a new product through HTTP post.<br />
-&gt; After getting json response from create_product.php, If success bit is 1 then list view is refreshed with newly added product.</p>
<pre class="brush: java; title: NewProductActivity.java; notranslate" title="NewProductActivity.java">package com.example.androidhive;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class NewProductActivity extends Activity {

	// Progress Dialog
	private ProgressDialog pDialog;

	JSONParser jsonParser = new JSONParser();
	EditText inputName;
	EditText inputPrice;
	EditText inputDesc;

	// url to create new product
	private static String url_create_product = "http://api.androidhive.info/android_connect/create_product.php";

	// JSON Node names
	private static final String TAG_SUCCESS = "success";

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

		// Edit Text
		inputName = (EditText) findViewById(R.id.inputName);
		inputPrice = (EditText) findViewById(R.id.inputPrice);
		inputDesc = (EditText) findViewById(R.id.inputDesc);

		// Create button
		Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);

		// button click event
		btnCreateProduct.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				// creating new product in background thread
				new CreateNewProduct().execute();
			}
		});
	}

	/**
	 * Background Async Task to Create new product
	 * */
	class CreateNewProduct extends AsyncTask&lt;String, String, String&gt; {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(NewProductActivity.this);
			pDialog.setMessage("Creating Product..");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		/**
		 * Creating product
		 * */
		protected String doInBackground(String... args) {
			String name = inputName.getText().toString();
			String price = inputPrice.getText().toString();
			String description = inputDesc.getText().toString();

			// Building Parameters
			List&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;();
			params.add(new BasicNameValuePair("name", name));
			params.add(new BasicNameValuePair("price", price));
			params.add(new BasicNameValuePair("description", description));

			// getting JSON Object
			// Note that create product url accepts POST method
			JSONObject json = jsonParser.makeHttpRequest(url_create_product,
					"POST", params);

			// check log cat fro response
			Log.d("Create Response", json.toString());

			// check for success tag
			try {
				int success = json.getInt(TAG_SUCCESS);

				if (success == 1) {
					// successfully created product
					Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
					startActivity(i);

					// closing this screen
					finish();
				} else {
					// failed to create product
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog once done
			pDialog.dismiss();
		}

	}
}
</pre>
<p></p>
<h3>Reading, Updating and Deleting a Single Product</h3>
<p><strong>9</strong>. If you notice the AllProductsActivity.java, In listview i am launching EditProductAcivity.java once a single list item is selected. So create xml file called <strong>edit_product.xml</strong> and create a form which is same as create_product.xml.</p>
<p><strong>edit_product.xml</strong></p>
<pre class="brush: xml; title: edit_product.xml; notranslate" title="edit_product.xml">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" &gt;

    &lt;!-- Name Label --&gt;
    &lt;TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Product Name"
        android:paddingLeft="10dip"
        android:paddingRight="10dip"
        android:paddingTop="10dip"
        android:textSize="17dip"/&gt;

    &lt;!-- Input Name --&gt;
	&lt;EditText android:id="@+id/inputName"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:layout_margin="5dip"
	    android:layout_marginBottom="15dip"
	    android:singleLine="true"/&gt;

	&lt;!-- Price Label --&gt;
    &lt;TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Price"
        android:paddingLeft="10dip"
        android:paddingRight="10dip"
        android:paddingTop="10dip"
        android:textSize="17dip"/&gt;

    &lt;!-- Input Price --&gt;
	&lt;EditText android:id="@+id/inputPrice"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:layout_margin="5dip"
	    android:layout_marginBottom="15dip"
	    android:singleLine="true"
	    android:inputType="numberDecimal"/&gt;

	&lt;!-- Description Label --&gt;
    &lt;TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Description"
        android:paddingLeft="10dip"
        android:paddingRight="10dip"
        android:paddingTop="10dip"
        android:textSize="17dip"/&gt;

    &lt;!-- Input description --&gt;
	&lt;EditText android:id="@+id/inputDesc"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:layout_margin="5dip"
	    android:layout_marginBottom="15dip"
	    android:lines="4"
	    android:gravity="top"/&gt;

	&lt;LinearLayout android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:orientation="horizontal"&gt;
	    &lt;!-- Button Create Product --&gt;
	&lt;Button android:id="@+id/btnSave"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="Save Changes"
	    android:layout_weight="1"/&gt;

	&lt;!-- Button Create Product --&gt;
	&lt;Button android:id="@+id/btnDelete"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="Delete"
	    android:layout_weight="1"/&gt;
	&lt;/LinearLayout&gt;

&lt;/LinearLayout&gt;
</pre>
<p><strong>10</strong>. Create a class file for edit_product.xml and name it as <strong>EditProductActivity.java</strong> and fill it with following code. In the following code</p>
<p>-&gt; First product id (<strong>pid</strong>) is read from the intent which is sent from listview.<br />
-&gt; A request is made to <strong>get_product_details.php</strong> and after getting product details in json format, I parsed the json and displayed in EditText.<br />
-&gt; After displaying product data in the form if user clicks on Save Changes Button, another HTTP request is made to <strong>update_product.php</strong> to store updated product data.<br />
-&gt; If the user selected Delete Product Button, HTTP request is made to <strong>delete_product.php</strong> and product is deleted from mysql database, and listview is refreshed with new product list.</p>
<pre class="brush: java; title: EditProductActivity.java; notranslate" title="EditProductActivity.java">package com.example.androidhive;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class EditProductActivity extends Activity {

	EditText txtName;
	EditText txtPrice;
	EditText txtDesc;
	EditText txtCreatedAt;
	Button btnSave;
	Button btnDelete;

	String pid;

	// Progress Dialog
	private ProgressDialog pDialog;

	// JSON parser class
	JSONParser jsonParser = new JSONParser();

	// single product url
	private static final String url_product_detials = "http://api.androidhive.info/android_connect/get_product_details.php";

	// url to update product
	private static final String url_update_product = "http://api.androidhive.info/android_connect/update_product.php";

	// url to delete product
	private static final String url_delete_product = "http://api.androidhive.info/android_connect/delete_product.php";

	// JSON Node names
	private static final String TAG_SUCCESS = "success";
	private static final String TAG_PRODUCT = "product";
	private static final String TAG_PID = "pid";
	private static final String TAG_NAME = "name";
	private static final String TAG_PRICE = "price";
	private static final String TAG_DESCRIPTION = "description";

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

		// save button
		btnSave = (Button) findViewById(R.id.btnSave);
		btnDelete = (Button) findViewById(R.id.btnDelete);

		// getting product details from intent
		Intent i = getIntent();

		// getting product id (pid) from intent
		pid = i.getStringExtra(TAG_PID);

		// Getting complete product details in background thread
		new GetProductDetails().execute();

		// save button click event
		btnSave.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// starting background task to update product
				new SaveProductDetails().execute();
			}
		});

		// Delete button click event
		btnDelete.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// deleting product in background thread
				new DeleteProduct().execute();
			}
		});

	}

	/**
	 * Background Async Task to Get complete product details
	 * */
	class GetProductDetails extends AsyncTask&lt;String, String, String&gt; {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(EditProductActivity.this);
			pDialog.setMessage("Loading product details. Please wait...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		/**
		 * Getting product details in background thread
		 * */
		protected String doInBackground(String... params) {

			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {
					// Check for success tag
					int success;
					try {
						// Building Parameters
						List&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;();
						params.add(new BasicNameValuePair("pid", pid));

						// getting product details by making HTTP request
						// Note that product details url will use GET request
						JSONObject json = jsonParser.makeHttpRequest(
								url_product_detials, "GET", params);

						// check your log for json response
						Log.d("Single Product Details", json.toString());

						// json success tag
						success = json.getInt(TAG_SUCCESS);
						if (success == 1) {
							// successfully received product details
							JSONArray productObj = json
									.getJSONArray(TAG_PRODUCT); // JSON Array

							// get first product object from JSON Array
							JSONObject product = productObj.getJSONObject(0);

							// product with this pid found
							// Edit Text
							txtName = (EditText) findViewById(R.id.inputName);
							txtPrice = (EditText) findViewById(R.id.inputPrice);
							txtDesc = (EditText) findViewById(R.id.inputDesc);

							// display product data in EditText
							txtName.setText(product.getString(TAG_NAME));
							txtPrice.setText(product.getString(TAG_PRICE));
							txtDesc.setText(product.getString(TAG_DESCRIPTION));

						}else{
							// product with pid not found
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			});

			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog once got all details
			pDialog.dismiss();
		}
	}

	/**
	 * Background Async Task to  Save product Details
	 * */
	class SaveProductDetails extends AsyncTask&lt;String, String, String&gt; {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(EditProductActivity.this);
			pDialog.setMessage("Saving product ...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		/**
		 * Saving product
		 * */
		protected String doInBackground(String... args) {

			// getting updated data from EditTexts
			String name = txtName.getText().toString();
			String price = txtPrice.getText().toString();
			String description = txtDesc.getText().toString();

			// Building Parameters
			List&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;();
			params.add(new BasicNameValuePair(TAG_PID, pid));
			params.add(new BasicNameValuePair(TAG_NAME, name));
			params.add(new BasicNameValuePair(TAG_PRICE, price));
			params.add(new BasicNameValuePair(TAG_DESCRIPTION, description));

			// sending modified data through http request
			// Notice that update product url accepts POST method
			JSONObject json = jsonParser.makeHttpRequest(url_update_product,
					"POST", params);

			// check json success tag
			try {
				int success = json.getInt(TAG_SUCCESS);

				if (success == 1) {
					// successfully updated
					Intent i = getIntent();
					// send result code 100 to notify about product update
					setResult(100, i);
					finish();
				} else {
					// failed to update product
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog once product uupdated
			pDialog.dismiss();
		}
	}

	/*****************************************************************
	 * Background Async Task to Delete Product
	 * */
	class DeleteProduct extends AsyncTask&lt;String, String, String&gt; {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(EditProductActivity.this);
			pDialog.setMessage("Deleting Product...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		/**
		 * Deleting product
		 * */
		protected String doInBackground(String... args) {

			// Check for success tag
			int success;
			try {
				// Building Parameters
				List&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;();
				params.add(new BasicNameValuePair("pid", pid));

				// getting product details by making HTTP request
				JSONObject json = jsonParser.makeHttpRequest(
						url_delete_product, "POST", params);

				// check your log for json response
				Log.d("Delete Product", json.toString());

				// json success tag
				success = json.getInt(TAG_SUCCESS);
				if (success == 1) {
					// product successfully deleted
					// notify previous activity by sending code 100
					Intent i = getIntent();
					// send result code 100 to notify about product deletion
					setResult(100, i);
					finish();
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog once product deleted
			pDialog.dismiss();

		}

	}
}
</pre>
<div class="image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/edit_product1.png" alt="android edit product" title="android edit product" width="580" height="628" class="alignnone size-full wp-image-1532" />
</div>
<div class="image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/deleting_product1.png" alt="android delete product" title="android delete product" width="580" height="628" class="alignnone size-full wp-image-1533" />
</div>
<p></p>
<h3>JSON Parser Class</h3>
<p>I used a JSON Parser class to get JSON from URL. This class supports two http request methods GET and POST to get json from url.</p>
<pre class="brush: java; title: JSONParser.java; notranslate" title="JSONParser.java">package com.example.androidhive;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

	static InputStream is = null;
	static JSONObject jObj = null;
	static String json = "";

	// constructor
	public JSONParser() {

	}

	// function get json from url
	// by making HTTP POST or GET mehtod
	public JSONObject makeHttpRequest(String url, String method,
			List&lt;NameValuePair&gt; params) {

		// Making HTTP request
		try {

			// check for request method
			if(method == "POST"){
				// request method is POST
				// defaultHttpClient
				DefaultHttpClient httpClient = new DefaultHttpClient();
				HttpPost httpPost = new HttpPost(url);
				httpPost.setEntity(new UrlEncodedFormEntity(params));

				HttpResponse httpResponse = httpClient.execute(httpPost);
				HttpEntity httpEntity = httpResponse.getEntity();
				is = httpEntity.getContent();

			}else if(method == "GET"){
				// request method is GET
				DefaultHttpClient httpClient = new DefaultHttpClient();
				String paramString = URLEncodedUtils.format(params, "utf-8");
				url += "?" + paramString;
				HttpGet httpGet = new HttpGet(url);

				HttpResponse httpResponse = httpClient.execute(httpGet);
				HttpEntity httpEntity = httpResponse.getEntity();
				is = httpEntity.getContent();
			}			

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			json = sb.toString();
		} catch (Exception e) {
			Log.e("Buffer Error", "Error converting result " + e.toString());
		}

		// try parse the string to a JSON object
		try {
			jObj = new JSONObject(json);
		} catch (JSONException e) {
			Log.e("JSON Parser", "Error parsing data " + e.toString());
		}

		// return JSON String
		return jObj;

	}
}
</pre>
<p>Run your project and test the application. You might get lot of errors. Always use <strong>Log Cat</strong> to debug your application, and if you couldn’t solve your errors please do comment here.</p>
<div style="display:none;">
This image is for thumbnail purpose<br />
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/banner_mysql_php1.png" alt="android connecting to mysql php" title="android connecting to mysql php" width="166" height="198" class="alignnone size-full wp-image-1534" />
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Android Spinner Dropdown Example</title>
		<link>http://www.androidhive.info/2012/04/android-spinner-dropdown-example/</link>
		<comments>http://www.androidhive.info/2012/04/android-spinner-dropdown-example/#comments</comments>
		<pubDate>Mon, 09 Apr 2012 13:01:30 +0000</pubDate>
		<dc:creator>Ravi Tamada</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Spinner]]></category>
		<category><![CDATA[UI]]></category>

		<guid isPermaLink="false">http://www.androidhive.info/?p=1393</guid>
		<description><![CDATA[This is a tutorial about simple spinner which allows to select an item from a drop down menu. I am displaying static data in spinner and after selecting an item from spinner a toast message will be shown. Creating new ...]]></description>
			<content:encoded><![CDATA[<p>This is a tutorial about simple spinner which allows to select an item from a drop down menu. I am displaying static data in spinner and after selecting an item from spinner a toast message will be shown.</p>
<div class="downloadsection"><a href="http://download.androidhive.info/download?code=Fqivt5trBseVpYRBkkUOq9GyoSZfINPAm6wrtyuiF8ja1cbcpV40Hj5qQmwMKYdOatnuTJv9IZS0hXsIoealUyQWTrSzfw8UYZ7pvePZRMs8ibKWw1" target="_blank"><img class="alignnone size-full wp-image-423" title="Download Code" src="http://www.androidhive.info/wp-content/uploads/2011/08/download_btn.png" alt="Download Code" width="173" height="41"></a></div>
<h3>Creating new Project</h3>
<p><strong>1</strong>. Create a new project and fill the required details <strong>File ⇒ New ⇒ Android Project</strong><br />
<strong>2</strong>. Open <strong>strings.xml</strong> file under <strong>resources folder</strong> and add following items. Add Spinner dialog tile in string resources.</p>
<pre class="brush: xml; title: strings.xml; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;resources&gt;
    &lt;string name=&quot;app_name&quot;&gt;AndroidSpinnerExample&lt;/string&gt;
    &lt;string name=&quot;spinner_title&quot;&gt;Select Category&lt;/string&gt;
&lt;/resources&gt;
</pre>
<p><strong>3</strong>. Now open your <strong>main.xml</strong> and design a simple layout with text label and a spinner.</p>
<pre class="brush: xml; title: main.xml; notranslate" title="main.xml">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="10dip"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"&gt;

    &lt;!-- Text Label --&gt;
    &lt;TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"
        android:text="Category:"
        android:layout_marginBottom="5dp"
    /&gt;

    &lt;!-- Spinner Element --&gt;
    &lt;Spinner
        android:id="@+id/spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:prompt="@string/spinner_title"
    /&gt;
&lt;/LinearLayout&gt;
</pre>
<p><strong>4</strong>. Open your main activity and extend it from <em>OnItemSelectedListener</em></p>
<pre class="brush: java; title: ; notranslate" title="">public class AndroidSpinnerExampleActivity extends Activity implements OnItemSelectedListener{
</pre>
<p><strong>5</strong>. After extending your activity from OnItemSelectedListener write the following code. In the following code i am creating a simple list with list of item needed to show in spinner. And finally i am attaching those items to spinner.</p>
<pre class="brush: java; title: AndroidSpinnerExampleActivity.java; notranslate">package com.androidhive.spinner;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class AndroidSpinnerExampleActivity extends Activity implements OnItemSelectedListener{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Spinner element
        Spinner spinner = (Spinner) findViewById(R.id.spinner);

        // Spinner click listener
        spinner.setOnItemSelectedListener(this);

        // Spinner Drop down elements
        List&amp;lt;String&amp;gt; categories = new ArrayList&amp;lt;String&amp;gt;();
        categories.add(&quot;Automobile&quot;);
        categories.add(&quot;Business Services&quot;);
        categories.add(&quot;Computers&quot;);
        categories.add(&quot;Education&quot;);
        categories.add(&quot;Personal&quot;);
        categories.add(&quot;Travel&quot;);

        // Creating adapter for spinner
		ArrayAdapter&amp;lt;String&amp;gt; dataAdapter = new ArrayAdapter&amp;lt;String&amp;gt;(this, android.R.layout.simple_spinner_item, categories);

		// Drop down layout style - list view with radio button
		dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		// attaching data adapter to spinner
		spinner.setAdapter(dataAdapter);
    }

    @Override
	public void onItemSelected(AdapterView&amp;lt;?&amp;gt; parent, View view, int position, long id) {
		// On selecting a spinner item
		String item = parent.getItemAtPosition(position).toString();

		// Showing selected spinner item
		Toast.makeText(parent.getContext(), &quot;Selected: &quot; + item, Toast.LENGTH_LONG).show();

	}

	public void onNothingSelected(AdapterView&amp;lt;?&amp;gt; arg0) {
		// TODO Auto-generated method stub

	}

}
</pre>
<p><strong>6</strong>. Run your project.</p>
<div class="image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/android_spinner.png" alt="android_spinner" title="android_spinner" width="580" height="638" class="alignnone size-full wp-image-1508" />
</div>
<p></p>
<div class="image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/android_spinner_dropdown.png" alt="android spinner dropdown" title="android spinner dropdown" width="580" height="638" class="alignnone size-full wp-image-1509" />
</div>
<div style="display: none">
This image is for thumbnail purpose<br />
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/banner_spinner_dropdown.png" alt="android spinner dropdown" title="android spinner dropdown" width="166" height="198" class="alignnone size-full wp-image-1510" />
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.androidhive.info/2012/04/android-spinner-dropdown-example/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Android Downloading File by Showing Progress Bar</title>
		<link>http://www.androidhive.info/2012/04/android-downloading-file-by-showing-progress-bar/</link>
		<comments>http://www.androidhive.info/2012/04/android-downloading-file-by-showing-progress-bar/#comments</comments>
		<pubDate>Sun, 01 Apr 2012 13:11:10 +0000</pubDate>
		<dc:creator>Ravi Tamada</dc:creator>
				<category><![CDATA[Async]]></category>
		<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Quick Tips]]></category>

		<guid isPermaLink="false">http://www.androidhive.info/?p=1395</guid>
		<description><![CDATA[When our application does a task that takes a considerable amount of time, it is common sense to show the progress of the task to the user. This is a good User Experience practice. In this tutorial i will be ...]]></description>
			<content:encoded><![CDATA[<p>
When our application does a task that takes a considerable amount of time, it is common sense to show the progress of the task to the user.<br />
This is a good User Experience practice. In this tutorial i will be discussing the implementation of a process-progress dialog.</p>
<p>As an example, i am displaying a progress bar that runs while the app downloads an image from the web. And once the image is downloaded<br />
completely i am showing the image in a image view. You could modify this example and try it with any file type you may wish. That could be fun!</p>
<div class="downloadsection"><a href="http://download.androidhive.info/download?code=P2RCIXw2DrgLJATVkBdQCxKenvaJAY75t12789iOF8ja1cbcpV40Hj5qQmwMKYdOatnuTJv9IZS0hxCtsui3U8RBCZjzq85TxTX40QBQ4ZEoeSN4pM" target="_blank"><img class="alignnone size-full wp-image-423" title="Download Code" src="http://www.androidhive.info/wp-content/uploads/2011/08/download_btn.png" alt="Download Code" width="173" height="41"></a></div>
<div class="downloadsection">
<iframe width="560" height="315" src="http://www.youtube.com/embed/5zkjQhZVfc0" frameborder="0" allowfullscreen></iframe></div>
<h3>Creating new Project</h3>
<p><strong>1</strong>. Create a new project and fill all the details. <strong>File ⇒ New ⇒ Android Project</strong><br />
<strong>2</strong>. Open your main.xml are create a button to show download progress bar. Also define a ImageView to show downloaded image. Paste the following code in your <strong>main.xml</strong></p>
<pre class="brush: xml; title: main.xml; 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:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot;
    android:orientation=&quot;vertical&quot; &gt;

    &lt;!-- Download Button --&gt;
    &lt;Button android:id=&quot;@+id/btnProgressBar&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:text=&quot;Download File with Progress Bar&quot;
        android:layout_marginTop=&quot;50dip&quot;/&gt;

    &lt;!-- Image view to show image after downloading --&gt;
    &lt;ImageView android:id=&quot;@+id/my_image&quot;
        android:layout_width=&quot;fill_parent&quot;
        android:layout_height=&quot;wrap_content&quot;/&gt;

&lt;/LinearLayout&gt;
</pre>
<p><strong>3</strong>. Now in your main activity class import necessary classes and buttons. I am starting a new asynctask to download the file after clicking on show progress bar button.</p>
<pre class="brush: java; title: ; notranslate">
public class AndroidDownloadFileByProgressBarActivity extends Activity {

	// button to show progress dialog
	Button btnShowProgress

	// Progress Dialog
	private ProgressDialog pDialog;

	// Progress dialog type (0 - for Horizontal progress bar)
	public static final int progress_bar_type = 0; 

	// File url to download
	private static String file_url = &quot;http://api.androidhive.info/progressdialog/hive.jpg&quot;;

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

		// show progress bar button
		btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
		// Image view to show image after downloading
		my_image = (ImageView) findViewById(R.id.my_image);

		/**
		 * Show Progress bar click event
		 * */
		btnShowProgress.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// starting new Async Task
				new DownloadFileFromURL().execute(file_url);
			}
		});
	}
</pre>
<p><strong>4</strong>. Progress Dialog can be shown using <a href="http://developer.android.com/reference/android/app/ProgressDialog.html" class="a-link" target="_blank">ProgressDialog</a> class. It is a subclass of normal <a href="http://developer.android.com/reference/android/app/AlertDialog.html" class="a-link" target="_blank">AlertDialog</a> class. So add an alert method in your main activity class.</p>
<pre class="brush: java; title: ; notranslate" title="">    /**
	 * Showing Dialog
	 * */
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case progress_bar_type:
			pDialog = new ProgressDialog(this);
			pDialog.setMessage("Downloading file. Please wait...");
			pDialog.setIndeterminate(false);
			pDialog.setMax(100);
			pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			pDialog.setCancelable(true);
			pDialog.show();
			return pDialog;
		default:
			return null;
		}
	}
</pre>
<p><strong>5</strong>. Now we need to add our Async Background thread to download file from url. In your main activity add a <strong>asynctask</strong> class and name it as <strong>DownloadFileFromURL()</strong>. After downloading image from the web i am reading the downloaded image from the sdcard and displaying in a imageview.</p>
<pre class="brush: java; title: ; notranslate" title="">	/**
	 * Background Async Task to download file
	 * */
	class DownloadFileFromURL extends AsyncTask&lt;String, String, String&gt; {

		/**
		 * Before starting background thread
		 * Show Progress Bar Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			showDialog(progress_bar_type);
		}

		/**
		 * Downloading file in background thread
		 * */
		@Override
		protected String doInBackground(String... f_url) {
			int count;
	        try {
	            URL url = new URL(f_url[0]);
	            URLConnection conection = url.openConnection();
	            conection.connect();
	            // getting file length
	            int lenghtOfFile = conection.getContentLength();

	            // input stream to read file - with 8k buffer
	            InputStream input = new BufferedInputStream(url.openStream(), 8192);

	            // Output stream to write file
	            OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");

	            byte data[] = new byte[1024];

	            long total = 0;

	            while ((count = input.read(data)) != -1) {
	                total += count;
	                // publishing the progress....
	                // After this onProgressUpdate will be called
	                publishProgress(""+(int)((total*100)/lenghtOfFile));

	                // writing data to file
	                output.write(data, 0, count);
	            }

	            // flushing output
	            output.flush();

	            // closing streams
	            output.close();
	            input.close();

	        } catch (Exception e) {
	        	Log.e("Error: ", e.getMessage());
	        }

	        return null;
		}

		/**
		 * Updating progress bar
		 * */
		protected void onProgressUpdate(String... progress) {
			// setting progress percentage
            pDialog.setProgress(Integer.parseInt(progress[0]));
       }

		/**
		 * After completing background task
		 * Dismiss the progress dialog
		 * **/
		@Override
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after the file was downloaded
			dismissDialog(progress_bar_type);

			// Displaying downloaded image into image view
			// Reading image path from sdcard
			String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
			// setting downloaded into image view
			my_image.setImageDrawable(Drawable.createFromPath(imagePath));
		}

	}
</pre>
<p><strong>6</strong>. Open your <strong>AndroidManifest.xml</strong> file and add <strong>internet connect permission</strong> and <strong>writing to sdcard permission</strong>.</p>
<pre class="brush: xml; title: AndroidManifest.xml; notranslate" title="AndroidManifest.xml">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidhive"
    android:versionCode="1"
    android:versionName="1.0" &gt;

    &lt;uses-sdk android:minSdkVersion="8" /&gt;

    &lt;application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" &gt;
        &lt;activity
            android:name=".AndroidDownloadFileByProgressBarActivity"
            android:label="@string/app_name" &gt;
            &lt;intent-filter&gt;
                &lt;action android:name="android.intent.action.MAIN" /&gt;

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

    &lt;!-- Permission: Allow Connect to Internet --&gt;
    &lt;uses-permission android:name="android.permission.INTERNET" /&gt;
    &lt;!-- Permission: Writing to SDCard --&gt;
    &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /&gt;

&lt;/manifest&gt;
</pre>
<p><strong>7</strong>. Run your Application and click on show progress bar button to see your progress bar. You can see the downloaded image in imageView once it is downloaded.</p>
<div class="image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/android_download_file_progress_bar.png" alt="android download file and showing progress bar" title="android download file and showing progress bar" width="580" height="597" class="alignnone size-full wp-image-1515" />
</div>
<p></p>
<h3>Final Code</h3>
<pre class="brush: java; title: ; notranslate" title="">package com.example.androidhive;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class AndroidDownloadFileByProgressBarActivity extends Activity {

	// button to show progress dialog
	Button btnShowProgress;

	// Progress Dialog
	private ProgressDialog pDialog;
	ImageView my_image;
	// Progress dialog type (0 - for Horizontal progress bar)
	public static final int progress_bar_type = 0; 

	// File url to download
	private static String file_url = "http://api.androidhive.info/progressdialog/hive.jpg";

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

		// show progress bar button
		btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
		// Image view to show image after downloading
		my_image = (ImageView) findViewById(R.id.my_image);
		/**
		 * Show Progress bar click event
		 * */
		btnShowProgress.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// starting new Async Task
				new DownloadFileFromURL().execute(file_url);
			}
		});
	}

	/**
	 * Showing Dialog
	 * */
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case progress_bar_type: // we set this to 0
			pDialog = new ProgressDialog(this);
			pDialog.setMessage("Downloading file. Please wait...");
			pDialog.setIndeterminate(false);
			pDialog.setMax(100);
			pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			pDialog.setCancelable(true);
			pDialog.show();
			return pDialog;
		default:
			return null;
		}
	}

	/**
	 * Background Async Task to download file
	 * */
	class DownloadFileFromURL extends AsyncTask&lt;String, String, String&gt; {

		/**
		 * Before starting background thread
		 * Show Progress Bar Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			showDialog(progress_bar_type);
		}

		/**
		 * Downloading file in background thread
		 * */
		@Override
		protected String doInBackground(String... f_url) {
			int count;
	        try {
	            URL url = new URL(f_url[0]);
	            URLConnection conection = url.openConnection();
	            conection.connect();
	            // this will be useful so that you can show a tipical 0-100% progress bar
	            int lenghtOfFile = conection.getContentLength();

	            // download the file
	            InputStream input = new BufferedInputStream(url.openStream(), 8192);

	            // Output stream
	            OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");

	            byte data[] = new byte[1024];

	            long total = 0;

	            while ((count = input.read(data)) != -1) {
	                total += count;
	                // publishing the progress....
	                // After this onProgressUpdate will be called
	                publishProgress(""+(int)((total*100)/lenghtOfFile));

	                // writing data to file
	                output.write(data, 0, count);
	            }

	            // flushing output
	            output.flush();

	            // closing streams
	            output.close();
	            input.close();

	        } catch (Exception e) {
	        	Log.e("Error: ", e.getMessage());
	        }

	        return null;
		}

		/**
		 * Updating progress bar
		 * */
		protected void onProgressUpdate(String... progress) {
			// setting progress percentage
            pDialog.setProgress(Integer.parseInt(progress[0]));
       }

		/**
		 * After completing background task
		 * Dismiss the progress dialog
		 * **/
		@Override
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after the file was downloaded
			dismissDialog(progress_bar_type);

			// Displaying downloaded image into image view
			// Reading image path from sdcard
			String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
			// setting downloaded into image view
			my_image.setImageDrawable(Drawable.createFromPath(imagePath));
		}

	}
}
</pre>
<div style="display:none">
This image is for thumbnail purpose<br />
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/banner_download_file_progress_bar.png" alt="android download file by showing progress bar" title="android download file by showing progress bar" width="166" height="198" class="alignnone size-full wp-image-1516" />
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.androidhive.info/2012/04/android-downloading-file-by-showing-progress-bar/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Android Facebook Connect Tutorial</title>
		<link>http://www.androidhive.info/2012/03/android-facebook-connect-tutorial/</link>
		<comments>http://www.androidhive.info/2012/03/android-facebook-connect-tutorial/#comments</comments>
		<pubDate>Mon, 19 Mar 2012 12:52:39 +0000</pubDate>
		<dc:creator>Ravi Tamada</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[facebook]]></category>

		<guid isPermaLink="false">http://www.androidhive.info/?p=1391</guid>
		<description><![CDATA[This tutorial is about integrating facebook into your android application. I am going to explain various steps like generating your application signature, registering facebook application, downloading facebook sdk and other steps. Here is an official documentation of facebook integration. Generating ...]]></description>
			<content:encoded><![CDATA[<p>This tutorial is about integrating facebook into your android application. I am going to explain various steps like generating your application signature, registering facebook application, downloading facebook sdk and other steps. Here is an official <a href="https://developers.facebook.com/docs/mobile/android/build/" target="_blank" class="ref-link">documentation</a> of facebook integration. </p>
<div class="downloadsection"><a href="http://download.androidhive.info/download?code=Qs5mR6aprabniJQblaIPWhn5rbSZvs21PXOopiou78ja1cbcpV40Hj5qQmwMKYdOatnuTJv9IZS0hdfWeBvF1z1IauMuTcBJ516zGPWDcOBkMgmR5F" target="_blank"><img class="alignnone size-full wp-image-423" title="Download Code" src="http://www.androidhive.info/wp-content/uploads/2011/08/download_btn.png" alt="Download Code" width="173" height="41"></a></div>
<div class="downloadsection">
<iframe width="560" height="315" src="http://www.youtube.com/embed/W3HyWJC0x5U" frameborder="0" allowfullscreen></iframe></div>
<h3>Generating App Signature for Facebook Settings</h3>
<p>To create facebook android native app you need to provide your Android application signature in facebook app settings. You can generate your application signature (keyhash) using <strong>keytool</strong> that comes with java. But to generate signature you need <strong>openssl</strong> installed on your pc. If you don’t have one download openssl from <a href="http://code.google.com/p/openssl-for-windows/downloads/detail?name=openssl-0.9.8k_WIN32.zip&#038;can=2&#038;q=" class="ref-link" target="_blank">here</a> and set it in your system environment path.</p>
<p> Open your command prompt (CMD) and run the following command to generate your keyhash. While generating hashkey it should ask you password. Give password as <strong>android</strong>. If it don’t ask for password your keystore path is incorrect.</p>
<pre class="brush: xml; title: ; notranslate">keytool -exportcert -alias androiddebugkey -keystore &quot;&amp;lt;path-to-users-directory&amp;gt;\.android\debug.keystore&quot; | openssl sha1 -binary | openssl base64
</pre>
<p>check the following command how i generated hashkey on my pc.</p>
<pre class="brush: xml; title: ; notranslate" title="">keytool -exportcert -alias androiddebugkey -keystore "C:\Users\Ravi\.android\debug.keystore" | openssl sha1 -binary | openssl base64
</pre>
<div class="article-post-image" <br="">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/android_facebook_generating_key_hash.png" alt="android facebook generating hash key app signature" title="android facebook generating hash key app signature" width="580" height="120" class="alignnone size-full wp-image-1487" /></div>
<p></p>
<h3>Registering your Facebook Application</h3>
<p>After generating your app signature successfully, register your facebook application by going to <a target="_blank" class="ref-link" href="https://developers.facebook.com/apps">create new facebook application</a> and fill out all the information needed. And select <strong>Native Android App</strong> and give your hashkey there which you generated  previously using keytool.</p>
<div class="article-post-image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/android_facebook_app_signature_java_keytool.png" alt="android facebook register app" title="android facebook register app" width="580" height="568" class="alignnone size-full wp-image-1488" />
</div>
<p>and note down your facebook <strong>App ID</strong></p>
<div class="article-post-image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/android_facebook_app_keys_settings.png" alt="android facebook app id" title="android facebook app id" width="580" height="472" class="alignnone size-full wp-image-1489" />
</div>
<p></p>
<h3>Creating Facebook Reference Project</h3>
<p>Once you are done with registering your facebook application, you need to download facebook SDK and create a new reference project. This reference project will be used to compile your actual project.</p>
<p><strong>1</strong>. Download <a href="https://github.com/facebook/facebook-android-sdk" class="ref-link" target="_blank">facebook android SDK</a> from git repositories.<br />
(git clone git://github.com/facebook/facebook-android-sdk.git)</p>
<p><strong>2</strong>. In your Eclipse goto <strong>File ⇒ Import ⇒ Existing Projects into Workspace</strong> and select the facebook project you downloaded from git repository.</p>
<div class="article-post-image" <br="">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/android_facebook_reference_project.png" alt="android facebook import project" title="android facebook import project" width="580" height="638" class="alignnone size-full wp-image-1491" />
</div>
<p></p>
<h3>Creating Your Facebook Connect Project</h3>
<p><strong>1</strong>. Create new Project in your Eclipse IDE. <strong>File ⇒ New ⇒ Android Project</strong> and fill out all the details.</p>
<p><strong>2</strong>. Now we need to add reference of this project to existing facebook project. <strong>Right Click on Project ⇒ Properties ⇒ android ⇒ Click on Add button ⇒ select your facebook project ⇒ Click Apply</strong>.</p>
<div class="article-post-image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/android_facebook_adding_reference_1.png" alt="android facebook adding reference project" title="android facebook adding reference project" width="580" height="540" class="alignnone size-full wp-image-1493" />
</div>
<div class="article-post-image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/android_facebook_adding_reference_2.png" alt="android facebook adding reference project" title="android facebook adding reference project" width="580" height="540" class="alignnone size-full wp-image-1494" />
</div>
<div class="article-post-image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/android_facebook_adding_reference_3.png" alt="android facebook adding reference project" title="android facebook adding reference project" width="580" height="540" class="alignnone size-full wp-image-1495" />
</div>
<p>Now our project setup is done. We can start coding our facebook application.</p>
<p><strong>3</strong>. Open your <strong>AndroidManifest.xml</strong> file add network connect permission in order to connect to internet.</p>
<pre class="brush: xml; title: ; notranslate" title="">&lt;uses-permission android:name="android.permission.INTERNET"/&gt;
</pre>
<pre class="brush: xml; title: AndroidManifest.xml; notranslate" title="AndroidManifest.xml">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.facebook.androidhive"
    android:versionCode="1"
    android:versionName="1.0" &gt;

    &lt;uses-sdk android:minSdkVersion="8" /&gt;

    &lt;application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" &gt;
        &lt;activity
            android:label="@string/app_name"
            android:name=".AndroidFacebookConnectActivity" &gt;
            &lt;intent-filter &gt;
                &lt;action android:name="android.intent.action.MAIN" /&gt;

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

    &lt;!-- Connect to Internet Permissions --&gt;
    &lt;uses-permission android:name="android.permission.INTERNET"/&gt;

&lt;/manifest&gt;
</pre>
<p><strong>4</strong>. Open Your Main Activity Class and initialize all the variables needed.</p>
<pre class="brush: java; title: ; notranslate">
public class AndroidFacebookConnectActivity extends Activity {

	// Your Facebook APP ID
	private static String APP_ID = &quot;308180782571605&quot;; // Replace your App ID here

	// Instance of Facebook Class
	private Facebook facebook;
	private AsyncFacebookRunner mAsyncRunner;
	String FILENAME = &quot;AndroidSSO_data&quot;;
	private SharedPreferences mPrefs;

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

		facebook = new Facebook(APP_ID);
		mAsyncRunner = new AsyncFacebookRunner(facebook);
</pre>
<p><strong>5</strong>. I created a simple interface which contains button to login, post to wall, show access tokens and logout for testing purpose.</p>
<h3>Login to Facebook Account</h3>
<p>I used a button to login into facebook account. In your activity write a click event for Login button click. Inside click event declare a function named <strong>loginToFacebook()</strong>;</p>
<p>Login button click event</p>
<pre class="brush: java; title: ; notranslate" title="">btnFbLogin.setOnClickListener(new View.OnClickListener() {
	@Override
	public void onClick(View v) {
			loginToFacebook();
		}
});
</pre>
<p>and function body for loginToFacebook() function is:</p>
<pre class="brush: java; title: ; notranslate" title="">	public void loginToFacebook() {
		mPrefs = getPreferences(MODE_PRIVATE);
		String access_token = mPrefs.getString("access_token", null);
		long expires = mPrefs.getLong("access_expires", 0);

		if (access_token != null) {
			facebook.setAccessToken(access_token);
		}

		if (expires != 0) {
			facebook.setAccessExpires(expires);
		}

		if (!facebook.isSessionValid()) {
			facebook.authorize(this,
					new String[] { "email", "publish_stream" },
					new DialogListener() {

						@Override
						public void onCancel() {
							// Function to handle cancel event
						}

						@Override
						public void onComplete(Bundle values) {
							// Function to handle complete event
							// Edit Preferences and update facebook acess_token
							SharedPreferences.Editor editor = mPrefs.edit();
							editor.putString("access_token",
									facebook.getAccessToken());
							editor.putLong("access_expires",
									facebook.getAccessExpires());
							editor.commit();
						}

						@Override
						public void onError(DialogError error) {
							// Function to handle error

						}

						@Override
						public void onFacebookError(FacebookError fberror) {
							// Function to handle Facebook errors

						}

					});
		}
	}
</pre>
<div class="article-post-image" <br="">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/android_facebook_login.png" alt="android facebook login" title="android facebook login" width="580" height="753" class="alignnone size-full wp-image-1497" />
</div>
<p></p>
<h3>Posting Message to Facebook Wall</h3>
<p>write a click event for post to wall button and inside click event write a function named <strong>postToWall()<br />
</strong></p>
<pre class="brush: java; title: ; notranslate" title="">btnPostToWall.setOnClickListener(new View.OnClickListener() {
	@Override
	public void onClick(View v) {
		postToWall();
	}
});
</pre>
<p>and function body for postToWall() function is:</p>
<pre class="brush: java; title: ; notranslate" title="">	public void postToWall() {
		// post on user's wall.
		facebook.dialog(this, "feed", new DialogListener() {

			@Override
			public void onFacebookError(FacebookError e) {
			}

			@Override
			public void onError(DialogError e) {
			}

			@Override
			public void onComplete(Bundle values) {
			}

			@Override
			public void onCancel() {
			}
		});

	}
</pre>
<div class="article-post-image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/android_facebook_posting_to_wall.png" alt="android facebook posting to wall" title="android facebook posting to wall" width="580" height="753" class="alignnone size-full wp-image-1498" />
</div>
<div class="article-post-image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/android_facebook_posting_wall_test.png" alt="android facebook posting to wall test" title="android facebook posting to wall test" width="580" height="209" class="alignnone size-full wp-image-1499" />
</div>
<p></p>
<h3>Getting Profile Information from Facebook</h3>
<p>To get profile information we need to make an api request to <a href="https://developers.facebook.com/docs/reference/api/" class="ref-link" target="_blank">facebook graph API</a>. Following is a function that will make an api request to <a href="https://graph.facebook.com/me/?access_token=AAAAAAITEghMBAHpMeQF01tn2qfZAe1Fdm5ksIs2Sj78PAkrZAZCLiZAqzsDPUbhaT2e0wwzUcQtGoKQms3EDY82UMTjx0zlZBjcgPfzZCYWaZAHs4NTjEhK" class="ref-link" target="_blank">facebook profile graph api</a> and will get profile information from facebook.</p>
<pre class="brush: java; title: ; notranslate" title="">getProfileInformation()
</pre>
<pre class="brush: java; title: ; notranslate" title="">	public void getProfileInformation() {
		mAsyncRunner.request("me", new RequestListener() {
			@Override
			public void onComplete(String response, Object state) {
				Log.d("Profile", response);
				String json = response;
				try {
					JSONObject profile = new JSONObject(json);
					// getting name of the user
					String name = profile.getString("name");
					// getting email of the user
					String email = profile.getString("email");

					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							Toast.makeText(getApplicationContext(), "Name: " + name + "\nEmail: " + email, Toast.LENGTH_LONG).show();
						}

					});

				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onIOException(IOException e, Object state) {
			}

			@Override
			public void onFileNotFoundException(FileNotFoundException e,
					Object state) {
			}

			@Override
			public void onMalformedURLException(MalformedURLException e,
					Object state) {
			}

			@Override
			public void onFacebookError(FacebookError e, Object state) {
			}
		});
	}
</pre>
<p>The above function will get json data from facebook. You need to parse the json in order to get individual profile data. If you are not aware of json parsing look at this article. <a href="http://www.androidhive.info/2012/01/android-json-parsing-tutorial/" class="ref-link" target="_blank">Android JSON Parsing Tutorial</a>. </p>
<p>The sample profile json from facebook will be like this</p>
<pre class="brush: java; title: ; notranslate" title="">{
   "id": "1464730016",
   "name": "Ravi Tamada",
   "first_name": "Ravi",
   "last_name": "Tamada",
   "link": "https://www.facebook.com/ravi8x",
   "username": "ravi8x",
   "birthday": "12/22/1988",
   "hometown": {
      "id": "112158005464147",
      "name": "Baruva"
   },
   "location": {
      "id": "102186159822587",
      "name": "Chennai, Tamil Nadu"
   },
   "bio": "Author: www.androidhive.info\r\nCo-author: www.9lessons.info",
   "work": [
      {
         "employer": {
            "id": "179366562092719",
            "name": "ByteAlly"
         },
         "location": {
            "id": "102186159822587",
            "name": "Chennai, Tamil Nadu"
         },
         "position": {
            "id": "124917314217511",
            "name": "Product Head"
         }
         ]
      }
   ],
   "favorite_athletes": [
      {
         "id": "18620649907",
         "name": "Virat Kohli"
      }
   ],
   "education": [
      {
         "school": {
            "id": "131587206873093",
            "name": "Raghu Engineering College (REC)"
         },
         "degree": {
            "id": "140065339390579",
            "name": "B.Tech"
         },
         "year": {
            "id": "142963519060927",
            "name": "2010"
         },
         "type": "Graduate School",
         "classes": [
            {
               "id": "192259410803415",
               "name": "2010",
               "with": [
                  {
                     "id": "584960408",
                     "name": "Santosh Patnaik"
                  }
               ],
               "from": {
                  "id": "584960408",
                  "name": "Santosh Patnaik"
               }
            }
         ]
      }
   ],
   "gender": "male",
   "relationship_status": "Single",
   "website": "www.androidhive.info\nwww.9lessons.info\nwww.twitter.com/ravitamada\nwww.about.me/rv",
   "timezone": 5.5,
   "locale": "en_US",
   "languages": [
      {
         "id": "106059522759137",
         "name": "English"
      },
      {
         "id": "107617475934611",
         "name": "Telugu"
      },
      {
         "id": "112969428713061",
         "name": "Hindi"
      },
      {
         "id": "343306413260",
         "name": "Tamil"
      }
   ],
   "verified": true,
   "updated_time": "2012-03-02T17:04:18+0000"
}
</pre>
<p></p>
<h3>Extending facebook Permissions</h3>
<p>If you want user’s other information like checkins, friends list etc., you need to extend facebook permissions while logging in user. Check list of <a href="https://developers.facebook.com/docs/reference/api/permissions/" class="ref-link" target="_blank">facebook permissions</a></p>
<pre class="brush: java; title: ; notranslate" title="">facebook.authorize(this, new String[] { "email", "publish_checkins", "publish_stream" },

      new DialogListener() {
           @Override
           public void onComplete(Bundle values) {}

           @Override
           public void onFacebookError(FacebookError error) {}

           @Override
           public void onError(DialogError e) {}

           @Override
           public void onCancel() {}
      }
);
</pre>
<p></p>
<h3>Getting Access Token</h3>
<p>Sometimes you might needed users access token for future purpose usage. Following code will give you currently logged in user access token.</p>
<pre class="brush: java; title: ; notranslate" title="">String access_token = facebook.getAccessToken();
</pre>
<p></p>
<h3>Logout from your app</h3>
<p>When user want to stop using facebook for your app, you can provide logout method to clear app state and invalidate access token. So further you can’t make request to facebook from your app.</p>
<pre class="brush: java; title: ; notranslate" title="">logoutFromFacebook();
</pre>
<pre class="brush: java; title: ; notranslate" title="">	public void logoutFromFacebook() {
		mAsyncRunner.logout(this, new RequestListener() {
			@Override
			public void onComplete(String response, Object state) {
				Log.d("Logout from Facebook", response);
				if (Boolean.parseBoolean(response) == true) {
					// User successfully Logged out
				}
			}

			@Override
			public void onIOException(IOException e, Object state) {
			}

			@Override
			public void onFileNotFoundException(FileNotFoundException e,
					Object state) {
			}

			@Override
			public void onMalformedURLException(MalformedURLException e,
					Object state) {
			}

			@Override
			public void onFacebookError(FacebookError e, Object state) {
			}
		});
	}
</pre>
<div style="display: none;">
This image is for thumbnail purpose<br />
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/banner_facebook_connect.png" alt="android facebook connect" title="android facebook connect" width="166" height="198" class="alignnone size-full wp-image-1502" />
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.androidhive.info/2012/03/android-facebook-connect-tutorial/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Android ListView with Load More Button</title>
		<link>http://www.androidhive.info/2012/03/android-listview-with-load-more-button/</link>
		<comments>http://www.androidhive.info/2012/03/android-listview-with-load-more-button/#comments</comments>
		<pubDate>Wed, 14 Mar 2012 12:36:27 +0000</pubDate>
		<dc:creator>Ravi Tamada</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[List View]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://www.androidhive.info/?p=1388</guid>
		<description><![CDATA[In this tutorial i am discussing about adding load more functionality to listview. It will be useful when you want to show data into paged format instead of loading huge amount of data into listview. Paged XML data For this ...]]></description>
			<content:encoded><![CDATA[<p>In this tutorial i am discussing about adding load more functionality to listview. It will be useful when you want to show data into paged format instead of loading huge amount of data into listview.</p>
<div class="downloadsection"><a href="http://download.androidhive.info/download?code=pTUA9FpisrZlI2DCR9C12v5dOIqfAMZI2bou1W3RF8Hy1cbcpV40Hj5qQmwMKYdOatnuTJv9IZSuioPDYysPB7ZU7y3wWICI1EM6TcpLOhlVPuCZpf" target="_blank"><img class="alignnone size-full wp-image-423" title="Download Code" src="http://www.androidhive.info/wp-content/uploads/2011/08/download_btn.png" alt="Download Code" width="173" height="41"></a></div>
<div class="downloadsection">
<iframe width="560" height="315" src="http://www.youtube.com/embed/etEZoJI5NjU" frameborder="0" allowfullscreen></iframe></div>
<h3>Paged XML data</h3>
<p>For this tutorial i am accessing an url which will give you paged XML by taking page number. Each page contains 20 results. You can access the xml by accessing url <a href="http://api.androidhive.info/list_paging/?page=1" target="_blank" class="ref-link">http://api.androidhive.info/list_paging/?page=1</a>. This url accepts “page” (page number – 1, 2, 3 ..) parameter as a GET variable. The sample response will be</p>
<pre class="brush: xml; title: ; notranslate">
&lt;menu&gt;
  &lt;item&gt;
     &lt;id&gt;1&lt;/id&gt;
     &lt;name&gt;sample list data 1&lt;/name&gt;
  &lt;/item&gt;
  &lt;item&gt;
     &lt;id&gt;2&lt;/id&gt;
     &lt;name&gt;sample list data 2&lt;/name&gt;
  &lt;/item&gt;
  .
  .
  .
  &lt;item&gt;
     &lt;id&gt;20&lt;/id&gt;
     &lt;name&gt;sample list data 20&lt;/name&gt;
  &lt;/item&gt;
&lt;item&gt;
</pre>
<p>You can prepare your own json or xml data with paging option. Example like displaying mysql data by taking page number.</p>
<h3>Adding button to ListView at the bottom</h3>
<p>You can add a view at the bottom of the listview by using <a class="ref-link" href="http://developer.android.com/reference/android/widget/ListView.html#addFooterView(android.view.View)" target="_blank">addFooterView</a> method. In this tutorial i am adding a button to the bottom of the listview.</p>
<pre class="brush: java; title: ; notranslate">// Getting listview from xml
ListView lv = (ListView) findViewById(R.id.list);

// Creating a button - Load More
Button btnLoadMore = new Button(this);
btnLoadMore.setText(&quot;Load More&quot;);

// Adding button to listview at footer
lv.addFooterView(btnLoadMore);
</pre>
<p></p>
<h3>Running a Asynchronous Background Thread</h3>
<p>We need a background thread while sending http request in order to get new data for listview. Following is a example of Async Background task.</p>
<pre class="brush: java; title: ; notranslate" title="">private class YourBackgroundThreadName extends AsyncTask&lt;Void, Void, Void&gt; {

		@Override
		protected void onPreExecute() {
		   // Before starting background task
		   // Show Progress Dialog etc,.
		}

		protected Void doInBackground(Void... unused) {
			runOnUiThread(new Runnable() {
				public void run() {
                // Run actual background task
                // Like sending HTTP Request - Parsing data
				}
			});
			return (null);
		}

		protected void onPostExecute(Void unused) {
			// On completing background task
			// closing progress dialog etc,.
		}
</pre>
<p>Calling a background thread</p>
<pre class="brush: java; title: ; notranslate" title="">// calling a background task
new YourBackgroundThreadName().execute();
</pre>
<p></p>
<h3>Create new Project</h3>
<p><strong>1</strong>. Create a new project by going to <strong>File ⇒ New ⇒ Android Project</strong> and fill all the required details.<br />
<strong>2</strong>. Open your <strong>main.xml</strong> and add a listview element in it.</p>
<pre class="brush: xml; title: main.xml; notranslate" title="main.xml">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"&gt;

    &lt;ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/&gt;

&lt;/LinearLayout&gt;
</pre>
<p><strong>3</strong>. Create a new XML layout for single list row item  under layouts folder.<br />
<strong>Right Click on res ⇒ New ⇒ Android XML File</strong> and fill with following code. Name the xml file as <strong>list_item.xml</strong></p>
<pre class="brush: xml; title: list_item.xml; notranslate" title="list_item.xml">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"&gt;  

        &lt;!-- List item name --&gt;
        &lt;TextView
            android:id="@+id/name"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textColor="#acacac"
            android:textStyle="bold"
            android:gravity="left"
            android:padding="10dip"
            android:textSize="16dp"&gt;
        &lt;/TextView&gt;
&lt;/LinearLayout&gt;
</pre>
<p><strong>4</strong>. Create a new class and name it as <strong>ListViewAdapter.java</strong> and fill with following code. This class is required to fill the listview with parsed xml data. I just displayed single text view.</p>
<pre class="brush: java; title: ListViewAdapter.java; notranslate" title="ListViewAdapter.java">package com.example.androidhive;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class ListViewAdapter extends BaseAdapter {

    private Activity activity;
    private ArrayList&lt;HashMap&lt;String, String&gt;&gt; data;
    private static LayoutInflater inflater=null;

    public ListViewAdapter(Activity a, ArrayList&lt;HashMap&lt;String, String&gt;&gt; d) {
        activity = a;
        data=d;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public int getCount() {
        return data.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        View vi=convertView;
        if(convertView==null)
            vi = inflater.inflate(R.layout.list_item, null);

        TextView name = (TextView)vi.findViewById(R.id.name);

        HashMap&lt;String, String&gt; item = new HashMap&lt;String, String&gt;();
        item = data.get(position);

        //Setting all values in listview
        name.setText(item.get("name"));
        return vi;
    }
}
</pre>
<p><strong>5</strong>. Now open your MainActivity try the following code. In the following code i am just displaying data into listview by parsing XML. Finally i added a load more button to the bottom to listview</p>
<pre class="brush: java; title: ; notranslate" title="">public class AndroidListViewWithLoadMoreButtonActivity extends Activity {

	// All variables
	XMLParser parser;
	Document doc;
	String xml;
	ListView lv;
	ListViewAdapter adapter;
	ArrayList&lt;HashMap&lt;String, String&gt;&gt; menuItems;
	ProgressDialog pDialog;

	private String URL = "http://api.androidhive.info/list_paging/?page=1";

	// XML node keys
	static final String KEY_ITEM = "item"; // parent node
	static final String KEY_ID = "id";
	static final String KEY_NAME = "name";

	// Flag for current page
	int current_page = 1;

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

		lv = (ListView) findViewById(R.id.list);

		menuItems = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;();

		parser = new XMLParser();
		xml = parser.getXmlFromUrl(URL); // getting XML
		doc = parser.getDomElement(xml); // getting DOM element

		NodeList nl = doc.getElementsByTagName(KEY_ITEM);
		// looping through all item nodes &lt;item&gt;
		for (int i = 0; i &lt; nl.getLength(); i++) {
			// creating new HashMap
			HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();
			Element e = (Element) nl.item(i);
			// adding each child node to HashMap key =&gt; value
			map.put(KEY_ID, parser.getValue(e, KEY_ID)); // id not using any where
			map.put(KEY_NAME, parser.getValue(e, KEY_NAME));

			// adding HashList to ArrayList
			menuItems.add(map);
		}

		// LoadMore button
		Button btnLoadMore = new Button(this);
		btnLoadMore.setText("Load More");

		// Adding Load More button to lisview at bottom
		lv.addFooterView(btnLoadMore);

		// Getting adapter
		adapter = new ListViewAdapter(this, menuItems);
		lv.setAdapter(adapter);
	}
}
</pre>
<div class="article-post-image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/output_listview_loadmore_button.png" alt="android listview with load more button" title="android listview with load more button" width="580" height="492" class="alignnone size-full wp-image-1477" />
</div>
<p></p>
<h3>Working with Load More Button</h3>
<p>Until now we displayed a simple listview with the first paged xml data. Now we need to add functionality to load more button. Add a click event listener to load more button and call a background thread which will append next paged data to listview.</p>
<p>Appending data to listview is nothing but appending data into adapter array. If you write your own Custom Adapter you need to call <strong>notifyDataSetChanged()</strong> on the adapter class in order to refresh list view. (For reference check this question: <a href="http://stackoverflow.com/questions/1917773/dynamic-listview-in-android-app" target="_blank" class="ref-link">Dynamic ListView in Android app</a>)</p>
<p><strong>6</strong>. Add a click event listener to LoadMore button in your MainActivity Class and start a new background thread once it is clicked.</p>
<pre class="brush: java; title: ; notranslate" title="">/**
* Listening to Load More button click event
* */
btnLoadMore.setOnClickListener(new View.OnClickListener() {
	@Override
	public void onClick(View arg0) {
		// Starting a new async task
		new loadMoreListView().execute();
	}
});
</pre>
<p><strong>7</strong>. Now after closing onCreate Method write a background thread class like below. In the following code i am making a HTTP request with next page number. After getting the new paged data i am parsing it and loading into listview. Once the listview is appended with new data i am setting scroll position using <strong>setSelectionFromTop()</strong> method.</p>
<pre class="brush: java; title: ; notranslate" title="">	/**
	 * Async Task that send a request to url
	 * Gets new list view data
	 * Appends to list view
	 * */
	private class loadMoreListView extends AsyncTask&lt;Void, Void, Void&gt; {

		@Override
		protected void onPreExecute() {
			// Showing progress dialog before sending http request
			pDialog = new ProgressDialog(
					AndroidListViewWithLoadMoreButtonActivity.this);
			pDialog.setMessage("Please wait..");
			pDialog.setIndeterminate(true);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		protected Void doInBackground(Void... unused) {
			runOnUiThread(new Runnable() {
				public void run() {
					// increment current page
					current_page += 1;

					// Next page request
					URL = "http://api.androidhive.info/list_paging/?page=" + current_page;

					xml = parser.getXmlFromUrl(URL); // getting XML
					doc = parser.getDomElement(xml); // getting DOM element

					NodeList nl = doc.getElementsByTagName(KEY_ITEM);
					// looping through all item nodes &lt;item&gt;
					for (int i = 0; i &lt; nl.getLength(); i++) {
						// creating new HashMap
						HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();
						Element e = (Element) nl.item(i);

						// adding each child node to HashMap key =&gt; value
						map.put(KEY_ID, parser.getValue(e, KEY_ID));
						map.put(KEY_NAME, parser.getValue(e, KEY_NAME));

						// adding HashList to ArrayList
						menuItems.add(map);
					}

					// get listview current position - used to maintain scroll position
					int currentPosition = lv.getFirstVisiblePosition();

					// Appending new data to menuItems ArrayList
					adapter = new ListViewAdapter(
							AndroidListViewWithLoadMoreButtonActivity.this,
							menuItems);

					// Setting new scroll position
					lv.setSelectionFromTop(currentPosition + 1, 0);
				}
			});
			return (null);
		}		

		protected void onPostExecute(Void unused) {
			// closing progress dialog
			pDialog.dismiss();
		}
	}
</pre>
<p></p>
<h3>Final Code</h3>
<p>The final code of the MainActivity class is</p>
<pre class="brush: java; title: ; notranslate" title="">package com.example.androidhive;

import java.util.ArrayList;
import java.util.HashMap;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class AndroidListViewWithLoadMoreButtonActivity extends Activity {

	// All variables
	XMLParser parser;
	Document doc;
	String xml;
	ListView lv;
	ListViewAdapter adapter;
	ArrayList&lt;HashMap&lt;String, String&gt;&gt; menuItems;
	ProgressDialog pDialog;

	private String URL = "http://api.androidhive.info/list_paging/?page=1";

	// XML node keys
	static final String KEY_ITEM = "item"; // parent node
	static final String KEY_ID = "id";
	static final String KEY_NAME = "name";

	// Flag for current page
	int current_page = 1;

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

		lv = (ListView) findViewById(R.id.list);

		menuItems = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;();

		parser = new XMLParser();
		xml = parser.getXmlFromUrl(URL); // getting XML
		doc = parser.getDomElement(xml); // getting DOM element

		NodeList nl = doc.getElementsByTagName(KEY_ITEM);
		// looping through all item nodes &lt;item&gt;
		for (int i = 0; i &lt; nl.getLength(); i++) {
			// creating new HashMap
			HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();
			Element e = (Element) nl.item(i);
			// adding each child node to HashMap key =&gt; value
			map.put(KEY_ID, parser.getValue(e, KEY_ID)); // id not using any where
			map.put(KEY_NAME, parser.getValue(e, KEY_NAME));

			// adding HashList to ArrayList
			menuItems.add(map);
		}

		// LoadMore button
		Button btnLoadMore = new Button(this);
		btnLoadMore.setText("Load More");

		// Adding Load More button to lisview at bottom
		lv.addFooterView(btnLoadMore);

		// Getting adapter
		adapter = new ListViewAdapter(this, menuItems);
		lv.setAdapter(adapter);

		/**
		 * Listening to Load More button click event
		 * */
		btnLoadMore.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// Starting a new async task
				new loadMoreListView().execute();
			}
		});

		/**
		 * Listening to listview single row selected
		 * **/
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView&lt;?&gt; parent, View view,
					int position, long id) {
				// getting values from selected ListItem
				String name = ((TextView) view.findViewById(R.id.name))
						.getText().toString();

				// Starting new intent
				Intent in = new Intent(getApplicationContext(),
						SingleMenuItemActivity.class);
				in.putExtra(KEY_NAME, name);
				startActivity(in);
			}
		});
	}

	/**
	 * Async Task that send a request to url
	 * Gets new list view data
	 * Appends to list view
	 * */
	private class loadMoreListView extends AsyncTask&lt;Void, Void, Void&gt; {

		@Override
		protected void onPreExecute() {
			// Showing progress dialog before sending http request
			pDialog = new ProgressDialog(
					AndroidListViewWithLoadMoreButtonActivity.this);
			pDialog.setMessage("Please wait..");
			pDialog.setIndeterminate(true);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		protected Void doInBackground(Void... unused) {
			runOnUiThread(new Runnable() {
				public void run() {
					// increment current page
					current_page += 1;

					// Next page request
					URL = "http://api.androidhive.info/list_paging/?page=" + current_page;

					xml = parser.getXmlFromUrl(URL); // getting XML
					doc = parser.getDomElement(xml); // getting DOM element

					NodeList nl = doc.getElementsByTagName(KEY_ITEM);
					// looping through all item nodes &lt;item&gt;
					for (int i = 0; i &lt; nl.getLength(); i++) {
						// creating new HashMap
						HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();
						Element e = (Element) nl.item(i);

						// adding each child node to HashMap key =&gt; value
						map.put(KEY_ID, parser.getValue(e, KEY_ID));
						map.put(KEY_NAME, parser.getValue(e, KEY_NAME));

						// adding HashList to ArrayList
						menuItems.add(map);
					}

					// get listview current position - used to maintain scroll position
					int currentPosition = lv.getFirstVisiblePosition();

					// Appending new data to menuItems ArrayList
					adapter = new ListViewAdapter(
							AndroidListViewWithLoadMoreButtonActivity.this,
							menuItems);
					lv.setAdapter(adapter);
					// Setting new scroll position
					lv.setSelectionFromTop(currentPosition + 1, 0);

				}
			});

			return (null);
		}

		protected void onPostExecute(Void unused) {
			// closing progress dialog
			pDialog.dismiss();
		}
	}
}
</pre>
<p></p>
<h3>Other Classes needed in this project</h3>
<p><strong>XMLParser.java</strong> – needed to parse xml data</p>
<pre class="brush: java; title: XMLParser.java; notranslate" title="XMLParser.java">package com.example.androidhive;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.util.Log;

public class XMLParser {

	// constructor
	public XMLParser() {

	}

	/**
	 * Getting XML from URL making HTTP request
	 * @param url string
	 * */
	public String getXmlFromUrl(String url) {
		String xml = null;

		try {
			// defaultHttpClient
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);

			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			xml = EntityUtils.toString(httpEntity);

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// return XML
		return xml;
	}

	/**
	 * Getting XML DOM element
	 * @param XML string
	 * */
	public Document getDomElement(String xml){
		Document doc = null;
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {

			DocumentBuilder db = dbf.newDocumentBuilder();

			InputSource is = new InputSource();
		        is.setCharacterStream(new StringReader(xml));
		        doc = db.parse(is); 

			} catch (ParserConfigurationException e) {
				Log.e("Error: ", e.getMessage());
				return null;
			} catch (SAXException e) {
				Log.e("Error: ", e.getMessage());
	            return null;
			} catch (IOException e) {
				Log.e("Error: ", e.getMessage());
				return null;
			}

	        return doc;
	}

	/** Getting node value
	  * @param elem element
	  */
	 public final String getElementValue( Node elem ) {
	     Node child;
	     if( elem != null){
	         if (elem.hasChildNodes()){
	             for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
	                 if( child.getNodeType() == Node.TEXT_NODE  ){
	                     return child.getNodeValue();
	                 }
	             }
	         }
	     }
	     return "";
	 }

	 /**
	  * Getting node value
	  * @param Element node
	  * @param key string
	  * */
	 public String getValue(Element item, String str) {
			NodeList n = item.getElementsByTagName(str);
			return this.getElementValue(n.item(0));
		}
}
</pre>
<div style="display:none">
This image is for thumbnail purpose.<br />
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/banner_listview_loadmore.png" alt="android listview with load more button" title="android listview with load more button" width="166" height="198" class="alignnone size-full wp-image-1481" />
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.androidhive.info/2012/03/android-listview-with-load-more-button/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Android Building Audio Player Tutorial</title>
		<link>http://www.androidhive.info/2012/03/android-building-audio-player-tutorial/</link>
		<comments>http://www.androidhive.info/2012/03/android-building-audio-player-tutorial/#comments</comments>
		<pubDate>Mon, 05 Mar 2012 12:27:45 +0000</pubDate>
		<dc:creator>Ravi Tamada</dc:creator>
				<category><![CDATA[Apps]]></category>
		<category><![CDATA[Beginner]]></category>
		<category><![CDATA[List View]]></category>
		<category><![CDATA[UI]]></category>

		<guid isPermaLink="false">http://www.androidhive.info/?p=1386</guid>
		<description><![CDATA[In this tutorial i am going to discuss building a simple audio player with basic controls like play, pause, forward, backward, next, previous, playlist and seekbar. This app basically will read all audio files(.mp3) from sdcard and plays selected song. ...]]></description>
			<content:encoded><![CDATA[<p>In this tutorial i am going to discuss building a simple audio player with basic controls like play, pause, forward, backward, next, previous, playlist and seekbar. This app basically will read all audio files(.mp3) from sdcard and plays selected song. For this tutorial i am referencing <a href="http://developer.android.com/reference/android/media/MediaPlayer.html" target="_blank" class="ref-link">MediaPlayer</a> and go through it if you need any documentation about usage.</p>
<div class="downloadsection"><a href="http://download.androidhive.info/download?code=EZIpVO8ziMeqfDr7ERYTFP60bKZU5Hj0utWu1W3R67yU1cbcpV40Hj5qQmwMKYdOatnuTJv9IZS0hc%3DC32fh6w3DBRpriN4AcJ4ifPll5IVKUxMgXz" target="_blank"><img class="alignnone size-full wp-image-423" title="Download Code" src="http://www.androidhive.info/wp-content/uploads/2011/08/download_btn.png" alt="Download Code" width="173" height="41"></a></div>
<div class="downloadsection">
<iframe width="560" height="315" src="http://www.youtube.com/embed/MnvxRVdVS9Q" frameborder="0" allowfullscreen></iframe></div>
<h3>Android MediaPlayer Class</h3>
<p>Android SDK is providing MediaPlayer Class to access android in built mediaplayer services like playing audio, video etc., In this tutorial i am using following functions of this class to control audio player.</p>
<pre class="brush: java; title: ; notranslate">MediaPlayer mp = new MediaPlayer();

// Set data source -
setDataSource(&quot;/sdcard/path_to_song&quot;);

// Play audio
mp.start();

// Pause audio
mp.pause();

// Reset mediaplayer
mp.reset();

// Get song length duration - in milliseconds
mp.getDuration();

// Get current duration - in milliseconds
mp.getCurrentDuration();

// Move song to particular second - used for Forward or Backward
mp.seekTo(positon); // position in milliseconds

// Check if song is playing or not
mp.isPlaying(); // returns true or false
</pre>
<p></p>
<h3>1. Designing the Audio Player Layout</h3>
<p>Design your audio player using some graphic designing softwares like photoshop. I used photoshop to design this app layout. If you are not aware of designing just download the required images from the internet. Following is a screenshot of the audio player which we are going to build in this tutorial. (You can find this layout PSD in the download code)</p>
<div class="image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/android_audio_player_interface.png" alt="Android building audio player" title="Android building audio player" width="580" height="485" class="alignnone size-full wp-image-1464" />
</div>
<p></p>
<h3>2. Preparing Required Icons and Images</h3>
<p>Once you are done with your app layout design, prepare the required icons and background images for the audio player application. Prepare your icons in different states like default, focused and pressed and place them all in your <strong>drawable</strong> folder.</p>
<div class="image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/audio_player_icons.png" alt="android audio player icons" title="android audio player icons" width="580" height="1132" class="alignnone size-full wp-image-1465" />
</div>
<p></p>
<h3>3. Writing XML layouts for ICON states (default/hover/pressed)</h3>
<p>After saving all the icons with different states, we need to write xml drawable for each icon. Following is a sample for play button. <strong>Save this file under drawable folder</strong>.</p>
<pre class="brush: xml; title: btn_play.xml; notranslate">
&lt;selector xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;
    &lt;item android:drawable=&quot;@drawable/img_btn_play_pressed&quot;
        android:state_focused=&quot;true&quot;
        android:state_pressed=&quot;true&quot; /&gt;
    &lt;item android:drawable=&quot;@drawable/img_btn_play_pressed&quot;
        android:state_focused=&quot;false&quot;
        android:state_pressed=&quot;true&quot; /&gt;
    &lt;item android:drawable=&quot;@drawable/img_btn_play_pressed&quot;
        	android:state_focused=&quot;true&quot; /&gt;
    &lt;item android:drawable=&quot;@drawable/img_btn_play&quot;
        android:state_focused=&quot;false&quot;
        android:state_pressed=&quot;false&quot; /&gt;
&lt;/selector&gt;
</pre>
<p><strong>Note</strong>: You need to write xml drawable for each icon you used for the player (like <strong>btn_pause.xml</strong>, <strong>btn_next.xml</strong> etc,.)</p>
<h3>4. Writing XML design for SeekBar</h3>
<p>In this tutorial i used customized SeekBar to show song progress. You can design the style of default SeekBar using xml styles. In your drawable folder create to xml files and type the following code.</p>
<p>Changing SeekBar background:</p>
<pre class="brush: xml; title: seekbar_progress_bg.xml; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
 &lt;layer-list xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;
    &lt;item&gt;
        &lt;clip&gt;
        &lt;bitmap xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
            android:src=&quot;@drawable/img_seekbar_progress_blue&quot;
            android:tileMode=&quot;repeat&quot;
            android:antialias=&quot;true&quot;
            android:dither=&quot;false&quot;
            android:filter=&quot;false&quot;
            android:gravity=&quot;left&quot;
        /&gt;
        &lt;/clip&gt;
    &lt;/item&gt;
&lt;/layer-list&gt;
</pre>
<p>Changing SeekBar Progress:</p>
<pre class="brush: xml; title: seekbar_progress.xml; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;layer-list xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;
    &lt;item android:id=&quot;@android:id/background&quot;
        android:drawable=&quot;@drawable/img_seekbar_bg&quot;
        android:dither=&quot;true&quot;&gt;
    &lt;/item&gt;
    &lt;item android:id=&quot;@android:id/secondaryProgress&quot;&gt;
        &lt;clip&gt;
            &lt;shape&gt;
                &lt;gradient
                    android:startColor=&quot;#80028ac8&quot;
                    android:centerColor=&quot;#80127fb1&quot;
                    android:centerY=&quot;0.75&quot;
                    android:endColor=&quot;#a004638f&quot;
                    android:angle=&quot;270&quot;
                /&gt;
            &lt;/shape&gt;
        &lt;/clip&gt;
    &lt;/item&gt;
    &lt;item
        android:id=&quot;@android:id/progress&quot;
        android:drawable=&quot;@drawable/seekbar_progress_bg&quot;
    /&gt;
&lt;/layer-list&gt;
</pre>
<p>Actual seekbar which uses above xml files:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;SeekBar
        	android:id=&quot;@+id/songProgressBar&quot;
	         android:layout_width=&quot;fill_parent&quot;
	         android:layout_height=&quot;wrap_content&quot;
	         android:layout_marginRight=&quot;20dp&quot;
	         android:layout_marginLeft=&quot;20dp&quot;
	         android:layout_marginBottom=&quot;20dp&quot;
	    	 android:layout_above=&quot;@id/player_footer_bg&quot;
	    	 android:thumb=&quot;@drawable/seek_handler&quot;
	    	 android:progressDrawable=&quot;@drawable/seekbar_progress&quot;
	    	 android:paddingLeft=&quot;6dp&quot;
	    	 android:paddingRight=&quot;6dp&quot;/&gt;
</pre>
<p></p>
<h3>5. Writing XML for Player Layout</h3>
<p>So far we created separate xml layout for all the icons, seekbar. Now we need to combine everything into single layout. Create a new file called <strong>player.xml</strong> under <strong>layout folder</strong> and paste the following code.</p>
<pre class="brush: xml; title: player.xml; notranslate">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    android:background=&quot;@color/player_background&quot;&gt; 

    &lt;!-- Player Header --&gt;
    &lt;LinearLayout
        android:id=&quot;@+id/player_header_bg&quot;
        android:layout_width=&quot;fill_parent&quot;
        android:layout_height=&quot;60dip&quot;
        android:background=&quot;@layout/bg_player_header&quot;
        android:layout_alignParentTop=&quot;true&quot;
        android:paddingLeft=&quot;5dp&quot;
        android:paddingRight=&quot;5dp&quot;&gt;

        &lt;!-- Song Title --&gt;
        &lt;TextView
            android:id=&quot;@+id/songTitle&quot;
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:layout_weight=&quot;1&quot;
            android:textColor=&quot;#04b3d2&quot;
            android:textSize=&quot;16dp&quot;
            android:paddingLeft=&quot;10dp&quot;
            android:textStyle=&quot;bold&quot;
            android:text=&quot;The Good, The Bad And The Ugly&quot;
            android:layout_marginTop=&quot;10dp&quot;/&gt;

        &lt;!-- Playlist button --&gt;
        &lt;ImageButton
            android:id=&quot;@+id/btnPlaylist&quot;
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;fill_parent&quot;
            android:src=&quot;@drawable/btn_playlist&quot;
            android:background=&quot;@null&quot;/&gt;
    &lt;/LinearLayout&gt;

    &lt;!-- Song Thumbnail Image --&gt;
    &lt;LinearLayout
        android:id=&quot;@+id/songThumbnail&quot;
        android:layout_width=&quot;fill_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:paddingTop=&quot;10dp&quot;
        android:paddingBottom=&quot;10dp&quot;
        android:gravity=&quot;center&quot;
        android:layout_below=&quot;@id/player_header_bg&quot;&gt;
    	&lt;ImageView android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:src=&quot;@drawable/adele&quot;/&gt;
    &lt;/LinearLayout&gt;

    &lt;!-- Player Footer --&gt;
    &lt;LinearLayout
        android:id=&quot;@+id/player_footer_bg&quot;
        android:layout_width=&quot;fill_parent&quot;
        android:layout_height=&quot;100dp&quot;
        android:layout_alignParentBottom=&quot;true&quot;
        android:background=&quot;@layout/bg_player_footer&quot;
        android:gravity=&quot;center&quot;&gt;

        &lt;!-- Player Buttons --&gt;
        &lt;LinearLayout
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:orientation=&quot;horizontal&quot;
            android:gravity=&quot;center_vertical&quot;
            android:background=&quot;@layout/rounded_corner&quot;
            android:paddingLeft=&quot;10dp&quot;
            android:paddingRight=&quot;10dp&quot;&gt;
            &lt;!-- Previous Button --&gt;
            &lt;ImageButton
                android:id=&quot;@+id/btnPrevious&quot;
                android:src=&quot;@drawable/btn_previous&quot;
                android:layout_width=&quot;wrap_content&quot;
                android:layout_height=&quot;wrap_content&quot;
                android:background=&quot;@null&quot;/&gt;
            &lt;!-- Backward Button --&gt;
            &lt;ImageButton
                android:id=&quot;@+id/btnBackward&quot;
                android:src=&quot;@drawable/btn_backward&quot;
                android:layout_width=&quot;wrap_content&quot;
                android:layout_height=&quot;wrap_content&quot;
                android:background=&quot;@null&quot;/&gt;
            &lt;!-- Play Button --&gt;
            &lt;ImageButton
                android:id=&quot;@+id/btnPlay&quot;
                android:src=&quot;@drawable/btn_play&quot;
                android:layout_width=&quot;wrap_content&quot;
                android:layout_height=&quot;wrap_content&quot;
                android:background=&quot;@null&quot;/&gt;
            &lt;!-- Forward Button --&gt;
            &lt;ImageButton
                android:id=&quot;@+id/btnForward&quot;
                android:src=&quot;@drawable/btn_forward&quot;
                android:layout_width=&quot;wrap_content&quot;
                android:layout_height=&quot;wrap_content&quot;
                android:background=&quot;@null&quot;/&gt;
            &lt;!-- Next Button --&gt;
            &lt;ImageButton
                android:id=&quot;@+id/btnNext&quot;
                android:src=&quot;@drawable/btn_next&quot;
                android:layout_width=&quot;wrap_content&quot;
                android:layout_height=&quot;wrap_content&quot;
                android:background=&quot;@null&quot;/&gt;
        &lt;/LinearLayout&gt;
    &lt;/LinearLayout&gt;

    &lt;!-- Progress Bar/Seek bar --&gt;
    &lt;SeekBar
        	android:id=&quot;@+id/songProgressBar&quot;
	         android:layout_width=&quot;fill_parent&quot;
	         android:layout_height=&quot;wrap_content&quot;
	         android:layout_marginRight=&quot;20dp&quot;
	         android:layout_marginLeft=&quot;20dp&quot;
	         android:layout_marginBottom=&quot;20dp&quot;
	    	 android:layout_above=&quot;@id/player_footer_bg&quot;
	    	 android:thumb=&quot;@drawable/seek_handler&quot;
	    	 android:progressDrawable=&quot;@drawable/seekbar_progress&quot;
	    	 android:paddingLeft=&quot;6dp&quot;
	    	 android:paddingRight=&quot;6dp&quot;/&gt;

    &lt;!-- Timer Display --&gt;
    &lt;LinearLayout
        android:id=&quot;@+id/timerDisplay&quot;
        android:layout_above=&quot;@id/songProgressBar&quot;
        android:layout_width=&quot;fill_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_marginRight=&quot;20dp&quot;
        android:layout_marginLeft=&quot;20dp&quot;
        android:layout_marginBottom=&quot;10dp&quot;&gt;
        &lt;!-- Current Duration Label --&gt;
        &lt;TextView
            android:id=&quot;@+id/songCurrentDurationLabel&quot;
            android:layout_width=&quot;fill_parent&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:layout_weight=&quot;1&quot;
            android:gravity=&quot;left&quot;
            android:textColor=&quot;#eeeeee&quot;
            android:textStyle=&quot;bold&quot;/&gt;
        &lt;!-- Total Duration Label --&gt;
        &lt;TextView
            android:id=&quot;@+id/songTotalDurationLabel&quot;
            android:layout_width=&quot;fill_parent&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:layout_weight=&quot;1&quot;
            android:gravity=&quot;right&quot;
            android:textColor=&quot;#04cbde&quot;
            android:textStyle=&quot;bold&quot;/&gt;
    &lt;/LinearLayout&gt;

    &lt;!-- Repeat / Shuffle buttons --&gt;
    &lt;LinearLayout
        android:layout_width=&quot;fill_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_above=&quot;@id/timerDisplay&quot;
        android:gravity=&quot;center&quot;&gt;
        &lt;!-- Repeat Button --&gt;
        &lt;ImageButton
            android:id=&quot;@+id/btnRepeat&quot;
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:src=&quot;@drawable/btn_repeat&quot;
            android:layout_marginRight=&quot;5dp&quot;
            android:background=&quot;@null&quot;/&gt;

        &lt;!-- Shuffle Button --&gt;
         &lt;ImageButton
            android:id=&quot;@+id/btnShuffle&quot;
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:src=&quot;@drawable/btn_shuffle&quot;
            android:layout_marginLeft=&quot;5dp&quot;
            android:background=&quot;@null&quot;/&gt;
    &lt;/LinearLayout&gt;
&lt;/RelativeLayout&gt;
</pre>
<p>The above xml will give following output layout.</p>
<div class="image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/banner_android_music_player.png" alt="android audio player" title="android audio player" width="580" height="600" class="alignnone size-full wp-image-1467" />
</div>
<p></p>
<h3>6. Writing XML for PlayList ListView</h3>
<p>Playlist is displayed using a listview. If you are not aware of listview go through this <a href="http://www.androidhive.info/2011/10/android-listview-tutorial/" target="_blank" class="ref-link">Android ListView Tutorial</a> and get an idea of listview layout.</p>
<p><strong>⇒</strong> Create an xml file under <strong>drawable folder</strong> and name it as <strong>list_selector.xml</strong> and type following code. This xml is used for gradient background for list item.</p>
<pre class="brush: xml; title: list_selector.xml; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;selector xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;
&lt;!-- Selector style for listrow --&gt;
&lt;item
 android:state_selected=&quot;false&quot;
    android:state_pressed=&quot;false&quot;
    android:drawable=&quot;@drawable/gradient_bg&quot; /&gt;
&lt;item android:state_pressed=&quot;true&quot;
    android:drawable=&quot;@drawable/gradient_bg_hover&quot; /&gt;
&lt;item android:state_selected=&quot;true&quot;
 android:state_pressed=&quot;false&quot;
    android:drawable=&quot;@drawable/gradient_bg_hover&quot; /&gt;
&lt;/selector&gt;
</pre>
<p><strong>⇒</strong> Create a new xml file under layout <strong>layout folder</strong> and name it as <strong>playlist.xml</strong> and type the following code. This xml file is for listview.</p>
<pre class="brush: xml; title: playlist.xml; 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:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot;
    android:orientation=&quot;vertical&quot;&gt;

    &lt;ListView
        android:id=&quot;@android:id/list&quot;
        android:layout_width=&quot;fill_parent&quot;
        android:layout_height=&quot;fill_parent&quot;
        android:divider=&quot;#242424&quot;
        android:dividerHeight=&quot;1dp&quot;
        android:listSelector=&quot;@drawable/list_selector&quot; /&gt;

&lt;/LinearLayout&gt;
</pre>
<p><strong>⇒</strong> Also create a new xml file under <strong>layout folder</strong> for single List Item. Name file as <strong>playlist_item.xml</strong> and type following code. This xml file is for single list item which holds song title.</p>
<pre class="brush: xml; title: playlist_item.xml; notranslate" title="playlist_item.xml">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:background="@drawable/list_selector"
    android:padding="5dp"&gt;
    &lt;TextView
        android:id="@+id/songTitle"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="16dp"
        android:padding="10dp"
        android:color="#f3f3f3"/&gt;
&lt;/LinearLayout&gt;
</pre>
<p>By using above layout we can achieve following list view by loading data into it.</p>
<div class="image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/play_list.png" alt="Android audio player playlist" title="Android audio player playlist" width="580" height="485" class="alignnone size-full wp-image-1469" />
</div>
<p></p>
<h3>7. Writing Class for reading MP3 files from SDcard</h3>
<p>So far we are done with static layouts for the player. Now the actual code starts.<br />
Create a new class file and name it as <strong>SongsManager.java</strong>. This class will read all the files from device sdcard and filters the files which are having <strong>.mp3</strong> extension.</p>
<pre class="brush: java; title: SongsManager.mp3; notranslate" title="SongsManager.mp3">package com.androidhive.musicplayer;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashMap;

public class SongsManager {
	// SDCard Path
	final String MEDIA_PATH = new String("/sdcard/");
	private ArrayList&lt;HashMap&lt;String, String&gt;&gt; songsList = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;();

	// Constructor
	public SongsManager(){

	}

	/**
	 * Function to read all mp3 files from sdcard
	 * and store the details in ArrayList
	 * */
	public ArrayList&lt;HashMap&lt;String, String&gt;&gt; getPlayList(){
		File home = new File(MEDIA_PATH);

		if (home.listFiles(new FileExtensionFilter()).length &gt; 0) {
			for (File file : home.listFiles(new FileExtensionFilter())) {
				HashMap&lt;String, String&gt; song = new HashMap&lt;String, String&gt;();
				song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
				song.put("songPath", file.getPath());

				// Adding each song to SongList
				songsList.add(song);
			}
		}
		// return songs list array
		return songsList;
	}

	/**
	 * Class to filter files which are having .mp3 extension
	 * */
	class FileExtensionFilter implements FilenameFilter {
		public boolean accept(File dir, String name) {
			return (name.endsWith(".mp3") || name.endsWith(".MP3"));
		}
	}
}
</pre>
<p></p>
<h3>8. Writing Class for PlayList ListView</h3>
<p>Create a new Activity class for playlist listview. Name the file as <strong>PlayListActivity.java</strong> This class will display list of songs in list layout by using <strong>SongsManager.java</strong> class</p>
<pre class="brush: java; title: PlayListActivity.java; notranslate" title="PlayListActivity.java">package com.androidhive.musicplayer;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class PlayListActivity extends ListActivity {
	// Songs list
	public ArrayList&lt;HashMap&lt;String, String&gt;&gt; songsList = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;();

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

		ArrayList&lt;HashMap&lt;String, String&gt;&gt; songsListData = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;();

		SongsManager plm = new SongsManager();
		// get all songs from sdcard
		this.songsList = plm.getPlayList();

		// looping through playlist
		for (int i = 0; i &lt; songsList.size(); i++) {
			// creating new HashMap
			HashMap&lt;String, String&gt; song = songsList.get(i);

			// adding HashList to ArrayList
			songsListData.add(song);
		}

		// Adding menuItems to ListView
		ListAdapter adapter = new SimpleAdapter(this, songsListData,
				R.layout.playlist_item, new String[] { "songTitle" }, new int[] {
						R.id.songTitle });

		setListAdapter(adapter);

		// selecting single ListView item
		ListView lv = getListView();
		// listening to single listitem click
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView&lt;?&gt; parent, View view,
					int position, long id) {
				// getting listitem index
				int songIndex = position;

				// Starting new intent
				Intent in = new Intent(getApplicationContext(),
						AndroidBuildingMusicPlayerActivity.class);
				// Sending songIndex to PlayerActivity
				in.putExtra("songIndex", songIndex);
				setResult(100, in);
				// Closing PlayListView
				finish();
			}
		});
	}
}
</pre>
<p></p>
<h3>9. Helper Class functions</h3>
<p>Create a new class called <strong>Utilities.java</strong> for handling extra work like <strong>converting time to progress percentage</strong> and vice-versa. Also it has function to <strong>convert millisecond to a timer string</strong> which will displayed on the seekbar of the player.</p>
<pre class="brush: java; title: Utilities.java; notranslate" title="Utilities.java">package com.androidhive.musicplayer;

public class Utilities {

	/**
	 * Function to convert milliseconds time to
	 * Timer Format
	 * Hours:Minutes:Seconds
	 * */
	public String milliSecondsToTimer(long milliseconds){
		String finalTimerString = "";
		String secondsString = "";

		// Convert total duration into time
		   int hours = (int)( milliseconds / (1000*60*60));
		   int minutes = (int)(milliseconds % (1000*60*60)) / (1000*60);
		   int seconds = (int) ((milliseconds % (1000*60*60)) % (1000*60) / 1000);
		   // Add hours if there
		   if(hours &gt; 0){
			   finalTimerString = hours + ":";
		   }

		   // Prepending 0 to seconds if it is one digit
		   if(seconds &lt; 10){
			   secondsString = "0" + seconds;
		   }else{
			   secondsString = "" + seconds;}

		   finalTimerString = finalTimerString + minutes + ":" + secondsString;

		// return timer string
		return finalTimerString;
	}

	/**
	 * Function to get Progress percentage
	 * @param currentDuration
	 * @param totalDuration
	 * */
	public int getProgressPercentage(long currentDuration, long totalDuration){
		Double percentage = (double) 0;

		long currentSeconds = (int) (currentDuration / 1000);
		long totalSeconds = (int) (totalDuration / 1000);

		// calculating percentage
		percentage =(((double)currentSeconds)/totalSeconds)*100;

		// return percentage
		return percentage.intValue();
	}

	/**
	 * Function to change progress to timer
	 * @param progress -
	 * @param totalDuration
	 * returns current duration in milliseconds
	 * */
	public int progressToTimer(int progress, int totalDuration) {
		int currentDuration = 0;
		totalDuration = (int) (totalDuration / 1000);
		currentDuration = (int) ((((double)progress) / 100) * totalDuration);

		// return current duration in milliseconds
		return currentDuration * 1000;
	}
}
</pre>
<p></p>
<h3>7. Writing Classes needed for Audio Player</h3>
<p>Open your main activity class which deals with main player interface and make the class <strong>implements</strong> from <strong>OnCompletionListener</strong>, <strong>SeekBar.OnSeekBarChangeListener</strong>.<br />
In this case my main activity name is AndroidBuildingMusicPlayerActivity.</p>
<pre class="brush: java; title: AndroidBuildingMusicPlayerActivity.java; notranslate" title="AndroidBuildingMusicPlayerActivity.java">public class AndroidBuildingMusicPlayerActivity extends Activity
       implements OnCompletionListener, SeekBar.OnSeekBarChangeListener {
</pre>
<p>Now declare all variable needed for this audio player class.</p>
<pre class="brush: java; title: AndroidBuildingMusicPlayerActivity.java; notranslate" title="AndroidBuildingMusicPlayerActivity.java">public class AndroidBuildingMusicPlayerActivity extends Activity
       implements OnCompletionListener, SeekBar.OnSeekBarChangeListener {

	private ImageButton btnPlay;
	private ImageButton btnForward;
	private ImageButton btnBackward;
	private ImageButton btnNext;
	private ImageButton btnPrevious;
	private ImageButton btnPlaylist;
	private ImageButton btnRepeat;
	private ImageButton btnShuffle;
	private SeekBar songProgressBar;
	private TextView songTitleLabel;
	private TextView songCurrentDurationLabel;
	private TextView songTotalDurationLabel;
	// Media Player
	private  MediaPlayer mp;
	// Handler to update UI timer, progress bar etc,.
	private Handler mHandler = new Handler();;
	private SongsManager songManager;
	private Utilities utils;
	private int seekForwardTime = 5000; // 5000 milliseconds
	private int seekBackwardTime = 5000; // 5000 milliseconds
	private int currentSongIndex = 0;
	private boolean isShuffle = false;
	private boolean isRepeat = false;
	private ArrayList&lt;HashMap&lt;String, String&gt;&gt; songsList = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;();
</pre>
<p>Now reference all buttons, images from xml layout to class.</p>
<pre class="brush: java; title: AndroidBuildingMusicPlayerActivity.java; notranslate" title="AndroidBuildingMusicPlayerActivity.java">// All player buttons
		btnPlay = (ImageButton) findViewById(R.id.btnPlay);
		btnForward = (ImageButton) findViewById(R.id.btnForward);
		btnBackward = (ImageButton) findViewById(R.id.btnBackward);
		btnNext = (ImageButton) findViewById(R.id.btnNext);
		btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
		btnPlaylist = (ImageButton) findViewById(R.id.btnPlaylist);
		btnRepeat = (ImageButton) findViewById(R.id.btnRepeat);
		btnShuffle = (ImageButton) findViewById(R.id.btnShuffle);
		songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
		songTitleLabel = (TextView) findViewById(R.id.songTitle);
		songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
		songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);

		// Mediaplayer
		mp = new MediaPlayer();
		songManager = new SongsManager();
		utils = new Utilities();

		// Listeners
		songProgressBar.setOnSeekBarChangeListener(this); // Important
		mp.setOnCompletionListener(this); // Important

		// Getting all songs list
		songsList = songManager.getPlayList();
</pre>
<p></p>
<h3>Launching PlayList</h3>
<p>Write click event listener to <strong>playlist button</strong>. On clicking playlist button we need to launch <strong>PlayListAcitivity.java</strong> and from listview on selecting a particular song we need get <strong>songIndex</strong>.</p>
<pre class="brush: java; title: AndroidBuildingMusicPlayerActivity.java; notranslate" title="AndroidBuildingMusicPlayerActivity.java">/**
		 * Button Click event for Play list click event
		 * Launches list activity which displays list of songs
		 * */
		btnPlaylist.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent i = new Intent(getApplicationContext(), PlayListActivity.class);
				startActivityForResult(i, 100);
			}
		});
</pre>
<p>To receive the selected songIndex add following fucntion. (Make sure that you added this function outside of onCreate method)</p>
<pre class="brush: java; title: AndroidBuildingMusicPlayerActivity.java; notranslate" title="AndroidBuildingMusicPlayerActivity.java">/**
	 * Receiving song index from playlist view
	 * and play the song
	 * */
	@Override
    protected void onActivityResult(int requestCode,
                                     int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 100){
         	 currentSongIndex = data.getExtras().getInt("songIndex");
         	 // play selected song
             playSong(currentSongIndex);
        }

    }
</pre>
<p></p>
<h3>Playing Song</h3>
<p>Add the following function to your class. This function accepts <strong>songIndex</strong> as param and plays it. Also when start playing a song it switches the play button to pause button state.</p>
<pre class="brush: java; title: AndroidBuildingMusicPlayerActivity.java; notranslate" title="AndroidBuildingMusicPlayerActivity.java">/**
	 * Function to play a song
	 * @param songIndex - index of song
	 * */
	public void  playSong(int songIndex){
		// Play song
		try {
        	mp.reset();
			mp.setDataSource(songsList.get(songIndex).get("songPath"));
			mp.prepare();
			mp.start();
			// Displaying Song title
			String songTitle = songsList.get(songIndex).get("songTitle");
        	songTitleLabel.setText(songTitle);

        	// Changing Button Image to pause image
			btnPlay.setImageResource(R.drawable.btn_pause);

			// set Progress bar values
			songProgressBar.setProgress(0);
			songProgressBar.setMax(100);

			// Updating progress bar
			updateProgressBar();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
</pre>
<p></p>
<h3>Forward / Backward button click events</h3>
<p>Add event listeners to Forward and Backward buttons which forwards or backwards song by specified seconds.</p>
<p>Forward button click event – moves song to specified number of seconds forward</p>
<pre class="brush: java; title: AndroidBuildingMusicPlayerActivity.java; notranslate" title="AndroidBuildingMusicPlayerActivity.java">/**
		 * Forward button click event
		 * Forwards song specified seconds
		 * */
		btnForward.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// get current song position
				int currentPosition = mp.getCurrentPosition();
				// check if seekForward time is lesser than song duration
				if(currentPosition + seekForwardTime &lt;= mp.getDuration()){
					// forward song
					mp.seekTo(currentPosition + seekForwardTime);
				}else{
					// forward to end position
					mp.seekTo(mp.getDuration());
				}
			}
		});
</pre>
<p>Backward button click event – moves song to specified number of seconds backward</p>
<pre class="brush: java; title: AndroidBuildingMusicPlayerActivity.java; notranslate" title="AndroidBuildingMusicPlayerActivity.java">/**
		 * Backward button click event
		 * Backward song to specified seconds
		 * */
		btnBackward.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// get current song position
				int currentPosition = mp.getCurrentPosition();
				// check if seekBackward time is greater than 0 sec
				if(currentPosition - seekBackwardTime &gt;= 0){
					// forward song
					mp.seekTo(currentPosition - seekBackwardTime);
				}else{
					// backward to starting position
					mp.seekTo(0);
				}

			}
		});
</pre>
<p></p>
<h3>Next / Back button click events</h3>
<p>Add click listeners to next and back buttons.</p>
<p>Next button click event – which plays next song from the playlist if presents else plays first song</p>
<pre class="brush: java; title: AndroidBuildingMusicPlayerActivity.java; notranslate" title="AndroidBuildingMusicPlayerActivity.java">/**
		 * Next button click event
		 * Plays next song by taking currentSongIndex + 1
		 * */
		btnNext.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// check if next song is there or not
				if(currentSongIndex &lt; (songsList.size() - 1)){
					playSong(currentSongIndex + 1);
					currentSongIndex = currentSongIndex + 1;
				}else{
					// play first song
					playSong(0);
					currentSongIndex = 0;
				}

			}
		});
</pre>
<p>Back button click event – which plays previous song if presents or plays last song</p>
<pre class="brush: java; title: AndroidBuildingMusicPlayerActivity.java; notranslate" title="AndroidBuildingMusicPlayerActivity.java">/**
		 * Back button click event
		 * Plays previous song by currentSongIndex - 1
		 * */
		btnPrevious.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if(currentSongIndex &gt; 0){
					playSong(currentSongIndex - 1);
					currentSongIndex = currentSongIndex - 1;
				}else{
					// play last song
					playSong(songsList.size() - 1);
					currentSongIndex = songsList.size() - 1;
				}

			}
		});
</pre>
<p></p>
<h3>Updating SeekBar progress and Timer</h3>
<p>To update progress bar timer i implemented a background thread which runs in background using a Handler. If you new to Handler follow this doc. <a href="http://developer.android.com/resources/articles/timed-ui-updates.html" class="ref-link" target="_blank">Updating the UI from a Timer</a></p>
<pre class="brush: java; title: AndroidBuildingMusicPlayerActivity.java; notranslate" title="AndroidBuildingMusicPlayerActivity.java">/**
	 * Update timer on seekbar
	 * */
	public void updateProgressBar() {
        mHandler.postDelayed(mUpdateTimeTask, 100);
    }	

	/**
	 * Background Runnable thread
	 * */
	private Runnable mUpdateTimeTask = new Runnable() {
		   public void run() {
			   long totalDuration = mp.getDuration();
			   long currentDuration = mp.getCurrentPosition();

			   // Displaying Total Duration time
			   songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
			   // Displaying time completed playing
			   songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));

			   // Updating progress bar
			   int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
			   //Log.d("Progress", ""+progress);
			   songProgressBar.setProgress(progress);

			   // Running this thread after 100 milliseconds
		       mHandler.postDelayed(this, 100);
		   }
		};

	/**
	 *
	 * */
	@Override
	public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {

	}

	/**
	 * When user starts moving the progress handler
	 * */
	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		// remove message Handler from updating progress bar
		mHandler.removeCallbacks(mUpdateTimeTask);
    }

	/**
	 * When user stops moving the progress hanlder
	 * */
	@Override
    public void onStopTrackingTouch(SeekBar seekBar) {
		mHandler.removeCallbacks(mUpdateTimeTask);
		int totalDuration = mp.getDuration();
		int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);

		// forward or backward to certain seconds
		mp.seekTo(currentPosition);

		// update timer progress again
		updateProgressBar();
    }
</pre>
<p></p>
<h3>Repeat button click event</h3>
<p>On clicking repeat button we need to set <strong>isRepeat</strong> to <strong>true</strong> and vice-versa. Also we need to change image source of repeat button to focused state.</p>
<pre class="brush: java; title: AndroidBuildingMusicPlayerActivity.java; notranslate" title="AndroidBuildingMusicPlayerActivity.java">/**
		 * Button Click event for Repeat button
		 * Enables repeat flag to true
		 * */
		btnRepeat.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if(isRepeat){
					isRepeat = false;
					Toast.makeText(getApplicationContext(), "Repeat is OFF", Toast.LENGTH_SHORT).show();
					btnRepeat.setImageResource(R.drawable.btn_repeat);
				}else{
					// make repeat to true
					isRepeat = true;
					Toast.makeText(getApplicationContext(), "Repeat is ON", Toast.LENGTH_SHORT).show();
					// make shuffle to false
					isShuffle = false;
					btnRepeat.setImageResource(R.drawable.btn_repeat_focused);
					btnShuffle.setImageResource(R.drawable.btn_shuffle);
				}
			}
		});
</pre>
<p></p>
<h3>Shuffle button click event</h3>
<p>On clicking shuffle button we need to set <strong>isShuffle</strong> to <strong>true</strong> and vice-versa. Also we need to change image source of shuffle button to focused state.</p>
<pre class="brush: java; title: AndroidBuildingMusicPlayerActivity.java; notranslate" title="AndroidBuildingMusicPlayerActivity.java">/**
		 * Button Click event for Shuffle button
		 * Enables shuffle flag to true
		 * */
		btnShuffle.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if(isShuffle){
					isShuffle = false;
					Toast.makeText(getApplicationContext(), "Shuffle is OFF", Toast.LENGTH_SHORT).show();
					btnShuffle.setImageResource(R.drawable.btn_shuffle);
				}else{
					// make repeat to true
					isShuffle= true;
					Toast.makeText(getApplicationContext(), "Shuffle is ON", Toast.LENGTH_SHORT).show();
					// make shuffle to false
					isRepeat = false;
					btnShuffle.setImageResource(R.drawable.btn_shuffle_focused);
					btnRepeat.setImageResource(R.drawable.btn_repeat);
				}
			}
		});
</pre>
<p></p>
<h3>Implementing song onCompletion Listener</h3>
<p>It is important to implement this listener which will notify you once the song is completed playing. In this method we need to play next song automatically depending on <strong>repeat</strong> and <strong>shuffle</strong> conditions.</p>
<pre class="brush: java; title: AndroidBuildingMusicPlayerActivity.java; notranslate" title="AndroidBuildingMusicPlayerActivity.java">/**
	 * On Song Playing completed
	 * if repeat is ON play same song again
	 * if shuffle is ON play random song
	 * */
	@Override
	public void onCompletion(MediaPlayer arg0) {

		// check for repeat is ON or OFF
		if(isRepeat){
			// repeat is on play same song again
			playSong(currentSongIndex);
		} else if(isShuffle){
			// shuffle is on - play a random song
			Random rand = new Random();
			currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;
			playSong(currentSongIndex);
		} else{
			// no repeat or shuffle ON - play next song
			if(currentSongIndex &lt; (songsList.size() - 1)){
				playSong(currentSongIndex + 1);
				currentSongIndex = currentSongIndex + 1;
			}else{
				// play first song
				playSong(0);
				currentSongIndex = 0;
			}
		}
	}
</pre>
<p></p>
<h3>Update your AndroidManifest.xml</h3>
<p>Update your AndroidManifest.xml to following code. Add <strong>android:configChanges=”keyboardHidden|orientation”</strong> to your main activity node.</p>
<pre class="brush: java; title: AndroidManifest.xml; notranslate" title="AndroidManifest.xml">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidhive.musicplayer"
    android:versionCode="1"
    android:versionName="1.0" &gt;

    &lt;uses-sdk android:minSdkVersion="8" /&gt;

    &lt;application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" &gt;
        &lt;activity
            android:name=".AndroidBuildingMusicPlayerActivity"
            android:label="@string/app_name"
            android:configChanges="keyboardHidden|orientation"&gt;
            &lt;intent-filter&gt;
                &lt;action android:name="android.intent.action.MAIN" /&gt;

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

        &lt;activity
            android:name=".PlayListActivity" /&gt;
    &lt;/application&gt;

&lt;/manifest&gt;
&lt;!-- AndroidBuildingMusicPlayerActivity --&gt;
</pre>
<p></p>
<h3>Final Code</h3>
<p>Following is complete code for the <strong>AndroidBuildingMusicPlayerActivity.java</strong> class.</p>
<pre class="brush: java; title: AndroidBuildingMusicPlayerActivity.java; notranslate" title="AndroidBuildingMusicPlayerActivity.java">package com.androidhive.musicplayer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidBuildingMusicPlayerActivity extends Activity implements OnCompletionListener, SeekBar.OnSeekBarChangeListener {

	private ImageButton btnPlay;
	private ImageButton btnForward;
	private ImageButton btnBackward;
	private ImageButton btnNext;
	private ImageButton btnPrevious;
	private ImageButton btnPlaylist;
	private ImageButton btnRepeat;
	private ImageButton btnShuffle;
	private SeekBar songProgressBar;
	private TextView songTitleLabel;
	private TextView songCurrentDurationLabel;
	private TextView songTotalDurationLabel;
	// Media Player
	private  MediaPlayer mp;
	// Handler to update UI timer, progress bar etc,.
	private Handler mHandler = new Handler();;
	private SongsManager songManager;
	private Utilities utils;
	private int seekForwardTime = 5000; // 5000 milliseconds
	private int seekBackwardTime = 5000; // 5000 milliseconds
	private int currentSongIndex = 0;
	private boolean isShuffle = false;
	private boolean isRepeat = false;
	private ArrayList&lt;HashMap&lt;String, String&gt;&gt; songsList = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;();

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

		// All player buttons
		btnPlay = (ImageButton) findViewById(R.id.btnPlay);
		btnForward = (ImageButton) findViewById(R.id.btnForward);
		btnBackward = (ImageButton) findViewById(R.id.btnBackward);
		btnNext = (ImageButton) findViewById(R.id.btnNext);
		btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
		btnPlaylist = (ImageButton) findViewById(R.id.btnPlaylist);
		btnRepeat = (ImageButton) findViewById(R.id.btnRepeat);
		btnShuffle = (ImageButton) findViewById(R.id.btnShuffle);
		songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
		songTitleLabel = (TextView) findViewById(R.id.songTitle);
		songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
		songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);

		// Mediaplayer
		mp = new MediaPlayer();
		songManager = new SongsManager();
		utils = new Utilities();

		// Listeners
		songProgressBar.setOnSeekBarChangeListener(this); // Important
		mp.setOnCompletionListener(this); // Important

		// Getting all songs list
		songsList = songManager.getPlayList();

		// By default play first song
		playSong(0);

		/**
		 * Play button click event
		 * plays a song and changes button to pause image
		 * pauses a song and changes button to play image
		 * */
		btnPlay.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// check for already playing
				if(mp.isPlaying()){
					if(mp!=null){
						mp.pause();
						// Changing button image to play button
						btnPlay.setImageResource(R.drawable.btn_play);
					}
				}else{
					// Resume song
					if(mp!=null){
						mp.start();
						// Changing button image to pause button
						btnPlay.setImageResource(R.drawable.btn_pause);
					}
				}

			}
		});

		/**
		 * Forward button click event
		 * Forwards song specified seconds
		 * */
		btnForward.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// get current song position
				int currentPosition = mp.getCurrentPosition();
				// check if seekForward time is lesser than song duration
				if(currentPosition + seekForwardTime &lt;= mp.getDuration()){
					// forward song
					mp.seekTo(currentPosition + seekForwardTime);
				}else{
					// forward to end position
					mp.seekTo(mp.getDuration());
				}
			}
		});

		/**
		 * Backward button click event
		 * Backward song to specified seconds
		 * */
		btnBackward.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// get current song position
				int currentPosition = mp.getCurrentPosition();
				// check if seekBackward time is greater than 0 sec
				if(currentPosition - seekBackwardTime &gt;= 0){
					// forward song
					mp.seekTo(currentPosition - seekBackwardTime);
				}else{
					// backward to starting position
					mp.seekTo(0);
				}

			}
		});

		/**
		 * Next button click event
		 * Plays next song by taking currentSongIndex + 1
		 * */
		btnNext.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// check if next song is there or not
				if(currentSongIndex &lt; (songsList.size() - 1)){
					playSong(currentSongIndex + 1);
					currentSongIndex = currentSongIndex + 1;
				}else{
					// play first song
					playSong(0);
					currentSongIndex = 0;
				}

			}
		});

		/**
		 * Back button click event
		 * Plays previous song by currentSongIndex - 1
		 * */
		btnPrevious.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if(currentSongIndex &gt; 0){
					playSong(currentSongIndex - 1);
					currentSongIndex = currentSongIndex - 1;
				}else{
					// play last song
					playSong(songsList.size() - 1);
					currentSongIndex = songsList.size() - 1;
				}

			}
		});

		/**
		 * Button Click event for Repeat button
		 * Enables repeat flag to true
		 * */
		btnRepeat.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if(isRepeat){
					isRepeat = false;
					Toast.makeText(getApplicationContext(), "Repeat is OFF", Toast.LENGTH_SHORT).show();
					btnRepeat.setImageResource(R.drawable.btn_repeat);
				}else{
					// make repeat to true
					isRepeat = true;
					Toast.makeText(getApplicationContext(), "Repeat is ON", Toast.LENGTH_SHORT).show();
					// make shuffle to false
					isShuffle = false;
					btnRepeat.setImageResource(R.drawable.btn_repeat_focused);
					btnShuffle.setImageResource(R.drawable.btn_shuffle);
				}
			}
		});

		/**
		 * Button Click event for Shuffle button
		 * Enables shuffle flag to true
		 * */
		btnShuffle.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if(isShuffle){
					isShuffle = false;
					Toast.makeText(getApplicationContext(), "Shuffle is OFF", Toast.LENGTH_SHORT).show();
					btnShuffle.setImageResource(R.drawable.btn_shuffle);
				}else{
					// make repeat to true
					isShuffle= true;
					Toast.makeText(getApplicationContext(), "Shuffle is ON", Toast.LENGTH_SHORT).show();
					// make shuffle to false
					isRepeat = false;
					btnShuffle.setImageResource(R.drawable.btn_shuffle_focused);
					btnRepeat.setImageResource(R.drawable.btn_repeat);
				}
			}
		});

		/**
		 * Button Click event for Play list click event
		 * Launches list activity which displays list of songs
		 * */
		btnPlaylist.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent i = new Intent(getApplicationContext(), PlayListActivity.class);
				startActivityForResult(i, 100);
			}
		});

	}

	/**
	 * Receiving song index from playlist view
	 * and play the song
	 * */
	@Override
    protected void onActivityResult(int requestCode,
                                     int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 100){
         	 currentSongIndex = data.getExtras().getInt("songIndex");
         	 // play selected song
             playSong(currentSongIndex);
        }

    }

	/**
	 * Function to play a song
	 * @param songIndex - index of song
	 * */
	public void  playSong(int songIndex){
		// Play song
		try {
        	mp.reset();
			mp.setDataSource(songsList.get(songIndex).get("songPath"));
			mp.prepare();
			mp.start();
			// Displaying Song title
			String songTitle = songsList.get(songIndex).get("songTitle");
        	songTitleLabel.setText(songTitle);

        	// Changing Button Image to pause image
			btnPlay.setImageResource(R.drawable.btn_pause);

			// set Progress bar values
			songProgressBar.setProgress(0);
			songProgressBar.setMax(100);

			// Updating progress bar
			updateProgressBar();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Update timer on seekbar
	 * */
	public void updateProgressBar() {
        mHandler.postDelayed(mUpdateTimeTask, 100);
    }	

	/**
	 * Background Runnable thread
	 * */
	private Runnable mUpdateTimeTask = new Runnable() {
		   public void run() {
			   long totalDuration = mp.getDuration();
			   long currentDuration = mp.getCurrentPosition();

			   // Displaying Total Duration time
			   songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
			   // Displaying time completed playing
			   songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));

			   // Updating progress bar
			   int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
			   //Log.d("Progress", ""+progress);
			   songProgressBar.setProgress(progress);

			   // Running this thread after 100 milliseconds
		       mHandler.postDelayed(this, 100);
		   }
		};

	/**
	 *
	 * */
	@Override
	public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {

	}

	/**
	 * When user starts moving the progress handler
	 * */
	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		// remove message Handler from updating progress bar
		mHandler.removeCallbacks(mUpdateTimeTask);
    }

	/**
	 * When user stops moving the progress hanlder
	 * */
	@Override
    public void onStopTrackingTouch(SeekBar seekBar) {
		mHandler.removeCallbacks(mUpdateTimeTask);
		int totalDuration = mp.getDuration();
		int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);

		// forward or backward to certain seconds
		mp.seekTo(currentPosition);

		// update timer progress again
		updateProgressBar();
    }

	/**
	 * On Song Playing completed
	 * if repeat is ON play same song again
	 * if shuffle is ON play random song
	 * */
	@Override
	public void onCompletion(MediaPlayer arg0) {

		// check for repeat is ON or OFF
		if(isRepeat){
			// repeat is on play same song again
			playSong(currentSongIndex);
		} else if(isShuffle){
			// shuffle is on - play a random song
			Random rand = new Random();
			currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;
			playSong(currentSongIndex);
		} else{
			// no repeat or shuffle ON - play next song
			if(currentSongIndex &lt; (songsList.size() - 1)){
				playSong(currentSongIndex + 1);
				currentSongIndex = currentSongIndex + 1;
			}else{
				// play first song
				playSong(0);
				currentSongIndex = 0;
			}
		}
	}

	@Override
	 public void onDestroy(){
	 super.onDestroy();
	    mp.release();
	 }

}
</pre>
<p></p>
<h3>Sending files to Emulator SDCard (For Testing)</h3>
<p>To test this app in your android emulator you need to load your emulator with some songs. You can send files to emulator sdcard using <strong>adb</strong> tool which comes with Android SDK.</p>
<p>Navigate to your <strong>android SDK folder/platform-tools/</strong> using command line. And using <strong>push</strong> command you can send files to sdcard. (Start your emulator before performing push command)</p>
<pre class="brush: xml; title: ; notranslate" title="">platform-tools&gt; adb push "c:\Songs\White Flag.mp3" "/sdcard/"
</pre>
<div class="image">
<img src="./Android Building Audio Player Tutorial_files/load_files_to_emulator_sdcard.png" alt="android load files to emulator sdcard" title="android load files to emulator sdcard" width="580" height="72" class="alignnone size-full wp-image-1675">
</div>
<p>Run your application.</p>
<div style="display: none;">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/banner_audio_player.png" alt="Android building music player" title="Android building music player" width="166" height="198" class="alignnone size-full wp-image-1471" />
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.androidhive.info/2012/03/android-building-audio-player-tutorial/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Android Using External Fonts</title>
		<link>http://www.androidhive.info/2012/02/android-using-external-fonts/</link>
		<comments>http://www.androidhive.info/2012/02/android-using-external-fonts/#comments</comments>
		<pubDate>Wed, 29 Feb 2012 12:02:14 +0000</pubDate>
		<dc:creator>Ravi Tamada</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Quick Tips]]></category>
		<category><![CDATA[UI]]></category>

		<guid isPermaLink="false">http://www.androidhive.info/?p=1384</guid>
		<description><![CDATA[Loading external fonts in your android application is very easy. It can be achieved with only two lines of code. Start a new Project 1. Create a new project and fill the required details. File ⇒ New Project. 2. Create ...]]></description>
			<content:encoded><![CDATA[<p><br/></p>
<p>Loading external fonts in your android application is very easy. It can be achieved with only two lines of code.</p>
<div class="downloadsection"><a href="http://download.androidhive.info/download?code=tTm7CvjyCzlgoDXNzIAMKogI18bIQqJB87uXvfGRF8ja1cbcpV40Hj5qQmwMKYdOatnuTJv9IZS0hc%3DTkxbSmJbpziSub1E00kqL8dmTCzpXDghmsI" target="_blank"><img class="alignnone size-full wp-image-423" title="Download Code" src="http://www.androidhive.info/wp-content/uploads/2011/08/download_btn.png" alt="Download Code" width="173" height="41"></a></div>
<h3>Start a new Project</h3>
<p><strong>1</strong>. Create a new project and fill the required details. <strong>File ⇒ New Project</strong>.<br />
<strong>2</strong>. Create a folder called fonts under <strong>assets</strong> folder and place all your fonts in it. (Folder name can be anything)</p>
<div class="article-post-image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/android_using_external_fonts.png" alt="android using external fonts" title="android using external fonts" width="580" height="458" class="alignnone size-full wp-image-1452" />
</div>
<p><strong>3</strong>. Open your main.xml and create a simple textview.</p>
<pre class="brush: xml; title: main.xml; 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:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot;
    android:orientation=&quot;vertical&quot;
    android:background=&quot;#222222&quot; &gt;

    &lt;TextView
        android:id=&quot;@+id/ghost&quot;
        android:layout_width=&quot;fill_parent&quot;
        android:layout_height=&quot;fill_parent&quot;
        android:textSize=&quot;70dip&quot;
        android:gravity=&quot;center&quot;
        android:textColor=&quot;#ef0000&quot;
        android:layout_marginTop=&quot;50dip&quot;
        android:text=&quot;ghost&quot; /&gt;

&lt;/LinearLayout&gt;
</pre>
<p><strong>4</strong>. Now open your MainActivity class file and try following code. In the following code i am  importing font from assets folder and using TypeFace class i am applying custom font on textview label.</p>
<pre class="brush: java; title: AndroidExternalFontsActivity.java; notranslate">package com.example.androidhive;

import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.TextView;

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

        // Font path
        String fontPath = &quot;fonts/Face Your Fears.ttf&quot;;

        // text view label
        TextView txtGhost = (TextView) findViewById(R.id.ghost);

        // Loading Font Face
        Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);

        // Applying font
        txtGhost.setTypeface(tf);
    }
}
</pre>
<p><strong>5</strong>. Run your project.</p>
<div class="article-post-image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/output_loading_external_fonts.png" alt="android loading external fonts" title="android loading external fonts" width="580" height="458" class="alignnone size-full wp-image-1453" />
</div>
<div class="" style="display: none;">
This image is for thumbnail purpose.<br />
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/banner_custom_fonts.png" alt="android using external fonts" title="android using external fonts" width="166" height="198" class="alignnone size-full wp-image-1454" />
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.androidhive.info/2012/02/android-using-external-fonts/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Android Custom ListView with Image and Text</title>
		<link>http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/</link>
		<comments>http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/#comments</comments>
		<pubDate>Mon, 20 Feb 2012 11:48:08 +0000</pubDate>
		<dc:creator>Ravi Tamada</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[List View]]></category>
		<category><![CDATA[UI]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://www.androidhive.info/?p=1382</guid>
		<description><![CDATA[This is a tutorial about customizing listview with an image and text. For this tutorial i am using some of the classes from this link. In this tutorial i explained how to load images from remote url and update into ...]]></description>
			<content:encoded><![CDATA[<p><br/></p>
<p>This is a tutorial about customizing listview with an image and text. For this tutorial i am using some of the classes from this <a href="https://github.com/thest1/LazyList" class="ref-link" target="_blank">link</a>. In this tutorial i explained how to load images from remote url and update into listview. Also explained how to design listview with your custom styles and colors instead of using default listview style.</p>
<div class="downloadsection"><a href="http://download.androidhive.info/download?code=vRb8xiuNu8vP2uVgTaIptE0eyQwaz8Yyp4yrty3RF8ja1cbcpV40Hj5qQmwMKYdOatnuTJv9IZS0drfb4cMEUmOu8gKcevL43BVwaVorhhCm3ypcwz" target="_blank"><img class="alignnone size-full wp-image-423" title="Download Code" src="http://www.androidhive.info/wp-content/uploads/2011/08/download_btn.png" alt="Download Code" width="173" height="41"></a></div>
<h3>The Sample XML</h3>
<p>For this tutorial i am using following sample XML which has some data and a thumbnail image url. You can get this XML by accessing <a href="http://api.androidhive.info/music/music.xml" class="ref-link" target="_blank">http://api.androidhive.info/music/music.xml</a></p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;music&gt;
    &lt;song&gt;
        &lt;id&gt;1&lt;/id&gt;
        &lt;title&gt;Someone Like You&lt;/title&gt;
        &lt;artist&gt;Adele&lt;/artist&gt;
        &lt;duration&gt;4:47&lt;/duration&gt;
	    &lt;plays&gt;1662&lt;/plays&gt;
	    &lt;thumb_url&gt;http://api.androidhive.info/music/images/adele.png&lt;/thumb_url&gt;
    &lt;/song&gt;
	&lt;song&gt;
        &lt;id&gt;2&lt;/id&gt;
        &lt;title&gt;Space Bound&lt;/title&gt;
        &lt;artist&gt;Eminem&lt;/artist&gt;
        &lt;duration&gt;4:38&lt;/duration&gt;
	    &lt;plays&gt;1900&lt;/plays&gt;
	    &lt;thumb_url&gt;http://api.androidhive.info/music/images/eminem.png&lt;/thumb_url&gt;
    &lt;/song&gt;
       .
       .
       .
       .
&lt;/music&gt;
</pre>
<p>Before going further make sure that you covered <a href="http://www.androidhive.info/2011/11/android-xml-parsing-tutorial/" class="ref-link" target="_blank">Android XML Parsing Tutorial</a> and <a href="http://www.androidhive.info/2011/10/android-listview-tutorial/" class="ref-link" target="_blank">Android ListView Tutorial</a> before</p>
<h3>Creating New Project</h3>
<p><strong>1</strong>. Create new project in your Eclipse IDE and fill all the details. <strong>File ⇒ New Project</strong><br />
<strong>2</strong>. If you notice the screen shots i designed listview with gradient background. To define gradient style create three new XML files under drawable folder and name them as <em>gradient_bg.xml</em>, <em>list_selector.xml</em> and <em>gradient_bg_hover.xml</em> and fill with following code. Also the thumbnail image has white background, for this i used <em>image_bg.xml</em><br />
Right Click and drawable-hdpi ⇒ New ⇒ Android XML File</p>
<p><strong>gradient_bg.xml</strong> – Default Background Gradient Style</p>
<pre class="brush: xml; title: gradient_bg.xml; notranslate" title="gradient_bg.xml">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"&gt;
  &lt;gradient
      android:startColor="#f1f1f2"
      android:centerColor="#e7e7e8"
      android:endColor="#cfcfcf"
      android:angle="270" /&gt;
&lt;/shape&gt;
</pre>
<p><strong>gradient_bg_hover.xml</strong> – Gradient Style for on hover state</p>
<pre class="brush: xml; title: gradient_bg_hover.xml; notranslate" title="gradient_bg_hover.xml">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"&gt;
  &lt;gradient
      android:startColor="#18d7e5"
      android:centerColor="#16cedb"
      android:endColor="#09adb9"
      android:angle="270" /&gt;
&lt;/shape&gt;
</pre>
<p><strong>list_selector.xml</strong> – Actual liststyle which combines the above two styles</p>
<pre class="brush: xml; title: list_selector.xml; notranslate" title="list_selector.xml">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;selector xmlns:android="http://schemas.android.com/apk/res/android"&gt;
	&lt;item
	 android:state_selected="false"
		android:state_pressed="false"
		android:drawable="@drawable/gradient_bg" /&gt;

	&lt;item android:state_pressed="true"
		android:drawable="@drawable/gradient_bg_hover" /&gt;

	&lt;item android:state_selected="true"
	 android:state_pressed="false"
		android:drawable="@drawable/gradient_bg_hover" /&gt;
&lt;/selector&gt;
</pre>
<p><strong>image_bg.xml</strong> – is for white border around the image in listview</p>
<pre class="brush: xml; title: image_bg.xml; notranslate" title="image_bg.xml">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;layer-list xmlns:android="http://schemas.android.com/apk/res/android" &gt;
    &lt;item&gt;
      &lt;shape
        android:shape="rectangle"&gt;
            &lt;stroke android:width="1dp" android:color="#dbdbdc" /&gt;
            &lt;solid android:color="#FFFFFF" /&gt;
        &lt;/shape&gt;
   &lt;/item&gt;
&lt;/layer-list&gt;
</pre>
<p><strong>3</strong>. Now open your <strong>main.xml</strong> file and define a listview in it.</p>
<pre class="brush: xml; title: main.xml; notranslate" title="main.xml">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"&gt;

    &lt;ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:divider="#b5b5b5"
        android:dividerHeight="1dp"
        android:listSelector="@drawable/list_selector" /&gt;

&lt;/LinearLayout&gt;
</pre>
<p><strong>4</strong>. Next step is to design single listrow. Create a new XML file under layout folder and name it as <em>list_row.xml</em>.<br />
<strong>Right Click ⇒ New ⇒ Android XML File</strong></p>
<p>In this tutorial i custom designed a listview which contains an image on leftside, time and arrow at the right end and a title in middle. I used RelativeLayout as parent node and placed all the remaining items using relative positioning properties. Check the following image</p>
<div class="article-post-image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/listview-sketch.png" alt="android custom listview" title="android custom listview" width="580" height="327" class="alignnone size-full wp-image-1438" />
</div>
<p><strong>list_row.xml</strong> – Single ListRow Layout</p>
<pre class="brush: xml; title: list_row.xml; notranslate" title="list_row.xml">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/list_selector"
    android:orientation="horizontal"
    android:padding="5dip" &gt;

	&lt;!--  ListRow Left sied Thumbnail image --&gt;
	&lt;LinearLayout android:id="@+id/thumbnail"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:padding="3dip"
        android:layout_alignParentLeft="true"
        android:background="@drawable/image_bg"
	    android:layout_marginRight="5dip"&gt;

		&lt;ImageView
			android:id="@+id/list_image"
	        android:layout_width="50dip"
	        android:layout_height="50dip"
	        android:src="@drawable/rihanna"/&gt;

	&lt;/LinearLayout&gt;

	&lt;!-- Title Of Song--&gt;
    &lt;TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/thumbnail"
        android:layout_toRightOf="@+id/thumbnail"
        android:text="Rihanna Love the way lie"
        android:textColor="#040404"
        android:typeface="sans"
        android:textSize="15dip"
        android:textStyle="bold"/&gt;

	&lt;!-- Artist Name --&gt;
    &lt;TextView
        android:id="@+id/artist"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/title"
        android:textColor="#343434"
        android:textSize="10dip"
        android:layout_marginTop="1dip"
        android:layout_toRightOf="@+id/thumbnail"
        android:text="Just gona stand there and ..." /&gt;

	&lt;!-- Rightend Duration --&gt;
    &lt;TextView
        android:id="@+id/duration"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@id/title"
        android:gravity="right"
        android:text="5:45"
        android:layout_marginRight="5dip"
        android:textSize="10dip"
        android:textColor="#10bcc9"
        android:textStyle="bold"/&gt;

     &lt;!-- Rightend Arrow --&gt;
     &lt;ImageView android:layout_width="wrap_content"
     	android:layout_height="wrap_content"
     	android:src="@drawable/arrow"
     	android:layout_alignParentRight="true"
     	android:layout_centerVertical="true"/&gt;

&lt;/RelativeLayout&gt;
</pre>
<p>The above XML will provide you output like below</p>
<div class="article-post-image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/listview_states.png" alt="android listview selected state" title="android listview selected state" width="580" height="338" class="alignnone size-full wp-image-1439" />
</div>
<p><strong>5</strong>. Until now we completed designing part of the listview. Next step is to parse the xml and update the data into listview. Create a new java class file in your src folder. <strong>Right Click on src ⇒ New ⇒ Class</strong> and name it as <em>LazyAdapter.java</em></p>
<pre class="brush: java; title: LazyAdapter.java; notranslate">package com.example.androidhive;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class LazyAdapter extends BaseAdapter {

    private Activity activity;
    private ArrayList&amp;lt;HashMap&amp;lt;String, String&amp;gt;&amp;gt; data;
    private static LayoutInflater inflater=null;
    public ImageLoader imageLoader; 

    public LazyAdapter(Activity a, ArrayList&amp;lt;HashMap&amp;lt;String, String&amp;gt;&amp;gt; d) {
        activity = a;
        data=d;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        imageLoader=new ImageLoader(activity.getApplicationContext());
    }

    public int getCount() {
        return data.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        View vi=convertView;
        if(convertView==null)
            vi = inflater.inflate(R.layout.list_row, null);

        TextView title = (TextView)vi.findViewById(R.id.title); // title
        TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
        TextView duration = (TextView)vi.findViewById(R.id.duration); // duration
        ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image

        HashMap&amp;lt;String, String&amp;gt; song = new HashMap&amp;lt;String, String&amp;gt;();
        song = data.get(position);

        // Setting all values in listview
        title.setText(song.get(CustomizedListView.KEY_TITLE));
        artist.setText(song.get(CustomizedListView.KEY_ARTIST));
        duration.setText(song.get(CustomizedListView.KEY_DURATION));
        imageLoader.DisplayImage(song.get(CustomizedListView.KEY_THUMB_URL), thumb_image);
        return vi;
    }
}
</pre>
<p><strong>6</strong>. Now open your <strong>MainActivity class</strong> and type the following code. In the following code i am getting xml from url and parsing it. While parsing i am storing all the xml data into HashMap and finally i am passing HashMap to LazyAdapter class.</p>
<pre class="brush: java; title: CustomizedListView.java; notranslate">package com.example.androidhive;

import java.util.ArrayList;
import java.util.HashMap;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class CustomizedListView extends Activity {
	// All static variables
	static final String URL = &quot;http://api.androidhive.info/music/music.xml&quot;;
	// XML node keys
	static final String KEY_SONG = &quot;song&quot;; // parent node
	static final String KEY_ID = &quot;id&quot;;
	static final String KEY_TITLE = &quot;title&quot;;
	static final String KEY_ARTIST = &quot;artist&quot;;
	static final String KEY_DURATION = &quot;duration&quot;;
	static final String KEY_THUMB_URL = &quot;thumb_url&quot;;

	ListView list;
    LazyAdapter adapter;

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

		ArrayList&amp;lt;HashMap&amp;lt;String, String&amp;gt;&amp;gt; songsList = new ArrayList&amp;lt;HashMap&amp;lt;String, String&amp;gt;&amp;gt;();

		XMLParser parser = new XMLParser();
		String xml = parser.getXmlFromUrl(URL); // getting XML from URL
		Document doc = parser.getDomElement(xml); // getting DOM element

		NodeList nl = doc.getElementsByTagName(KEY_SONG);
		// looping through all song nodes &amp;lt;song&amp;gt;
		for (int i = 0; i &amp;lt; nl.getLength(); i++) {
			// creating new HashMap
			HashMap&amp;lt;String, String&amp;gt; map = new HashMap&amp;lt;String, String&amp;gt;();
			Element e = (Element) nl.item(i);
			// adding each child node to HashMap key =&amp;gt; value
			map.put(KEY_ID, parser.getValue(e, KEY_ID));
			map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
			map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
			map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
			map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));

			// adding HashList to ArrayList
			songsList.add(map);
		}

		list=(ListView)findViewById(R.id.list);

		// Getting adapter by passing xml data ArrayList
        adapter=new LazyAdapter(this, songsList);
        list.setAdapter(adapter);

        // Click event for single list row
        list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView&amp;lt;?&amp;gt; parent, View view,
					int position, long id) {

			}
		});
	}
}
</pre>
<h3>Add Permissions in AndroidManifest.xml</h3>
<p>Open your <strong>AndroidManifest.xml</strong> file add two permissons <strong>INTERNET</strong> and <strong>WRITE_EXTERNAL_STORAGE</strong>.</p>
<pre class="brush: xml; title: AndroidManifest.xml; notranslate" title="AndroidManifest.xml">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
	package="com.example.androidhive" android:versionCode="1"
	android:versionName="1.0"&gt;
	&lt;uses-sdk android:minSdkVersion="8" /&gt;

	&lt;application android:icon="@drawable/icon" android:label="@string/app_name"&gt;
		&lt;activity android:name=".CustomizedListView" android:label="@string/app_name"&gt;
			&lt;intent-filter&gt;
				&lt;action android:name="android.intent.action.MAIN" /&gt;
				&lt;category android:name="android.intent.category.LAUNCHER" /&gt;
			&lt;/intent-filter&gt;
		&lt;/activity&gt;
	&lt;/application&gt;

	&lt;uses-permission android:name="android.permission.INTERNET" /&gt;
	&lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /&gt;
&lt;/manifest&gt;
</pre>
<p>Also you need 5 more classes in order to run this project. I am giving the code for each class at the end of the article. After adding all the classes if you run the project it will show output like below<br />
<strong>ListView Default State</strong></p>
<div class="article-post-image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/android_custom_listview.png" alt="android customized listview" title="android customized listview" width="580" height="700" class="alignnone size-full wp-image-1440" />
</div>
<p><strong>ListView on Select State</strong></p>
<div class="article-post-image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/android_custom_listview_onhover.png" alt="android customized listview hover" title="android customized listview hover" width="580" height="700" class="alignnone size-full wp-image-1441" />
</div>
<h3>Other Classes you needed to run this project</h3>
<p>You also need to include following class which deals functionalities like fetching images from WEB, storing them in cache and clearing cache etc., Make sure that you included following files in your project.</p>
<p><strong>XMLParser.java</strong></p>
<pre class="brush: java; title: XMLParser.java; notranslate">package com.example.androidhive;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.util.Log;

public class XMLParser {

	// constructor
	public XMLParser() {

	}

	/**
	 * Getting XML from URL making HTTP request
	 * @param url string
	 * */
	public String getXmlFromUrl(String url) {
		String xml = null;

		try {
			// defaultHttpClient
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);

			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			xml = EntityUtils.toString(httpEntity);

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// return XML
		return xml;
	}

	/**
	 * Getting XML DOM element
	 * @param XML string
	 * */
	public Document getDomElement(String xml){
		Document doc = null;
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {

			DocumentBuilder db = dbf.newDocumentBuilder();

			InputSource is = new InputSource();
		        is.setCharacterStream(new StringReader(xml));
		        doc = db.parse(is); 

			} catch (ParserConfigurationException e) {
				Log.e(&quot;Error: &quot;, e.getMessage());
				return null;
			} catch (SAXException e) {
				Log.e(&quot;Error: &quot;, e.getMessage());
	            return null;
			} catch (IOException e) {
				Log.e(&quot;Error: &quot;, e.getMessage());
				return null;
			}

	        return doc;
	}

	/** Getting node value
	  * @param elem element
	  */
	 public final String getElementValue( Node elem ) {
	     Node child;
	     if( elem != null){
	         if (elem.hasChildNodes()){
	             for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
	                 if( child.getNodeType() == Node.TEXT_NODE  ){
	                     return child.getNodeValue();
	                 }
	             }
	         }
	     }
	     return &quot;&quot;;
	 }

	 /**
	  * Getting node value
	  * @param Element node
	  * @param key string
	  * */
	 public String getValue(Element item, String str) {
			NodeList n = item.getElementsByTagName(str);
			return this.getElementValue(n.item(0));
		}
}
</pre>
<p><strong>ImageLoader.java</strong></p>
<pre class="brush: java; title: ImageLoader.java; notranslate">package com.example.androidhive;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;

public class ImageLoader {

    MemoryCache memoryCache=new MemoryCache();
    FileCache fileCache;
    private Map&amp;lt;ImageView, String&amp;gt; imageViews=Collections.synchronizedMap(new WeakHashMap&amp;lt;ImageView, String&amp;gt;());
    ExecutorService executorService; 

    public ImageLoader(Context context){
        fileCache=new FileCache(context);
        executorService=Executors.newFixedThreadPool(5);
    }

    final int stub_id = R.drawable.no_image;
    public void DisplayImage(String url, ImageView imageView)
    {
        imageViews.put(imageView, url);
        Bitmap bitmap=memoryCache.get(url);
        if(bitmap!=null)
            imageView.setImageBitmap(bitmap);
        else
        {
            queuePhoto(url, imageView);
            imageView.setImageResource(stub_id);
        }
    }

    private void queuePhoto(String url, ImageView imageView)
    {
        PhotoToLoad p=new PhotoToLoad(url, imageView);
        executorService.submit(new PhotosLoader(p));
    }

    private Bitmap getBitmap(String url)
    {
        File f=fileCache.getFile(url);

        //from SD cache
        Bitmap b = decodeFile(f);
        if(b!=null)
            return b;

        //from web
        try {
            Bitmap bitmap=null;
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is=conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Exception ex){
           ex.printStackTrace();
           return null;
        }
    }

    //decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f){
        try {
            //decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);

            //Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE=70;
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2&amp;lt;REQUIRED_SIZE || height_tmp/2&amp;lt;REQUIRED_SIZE)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale*=2;
            }

            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {}
        return null;
    }

    //Task for the queue
    private class PhotoToLoad
    {
        public String url;
        public ImageView imageView;
        public PhotoToLoad(String u, ImageView i){
            url=u;
            imageView=i;
        }
    }

    class PhotosLoader implements Runnable {
        PhotoToLoad photoToLoad;
        PhotosLoader(PhotoToLoad photoToLoad){
            this.photoToLoad=photoToLoad;
        }

        @Override
        public void run() {
            if(imageViewReused(photoToLoad))
                return;
            Bitmap bmp=getBitmap(photoToLoad.url);
            memoryCache.put(photoToLoad.url, bmp);
            if(imageViewReused(photoToLoad))
                return;
            BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
            Activity a=(Activity)photoToLoad.imageView.getContext();
            a.runOnUiThread(bd);
        }
    }

    boolean imageViewReused(PhotoToLoad photoToLoad){
        String tag=imageViews.get(photoToLoad.imageView);
        if(tag==null || !tag.equals(photoToLoad.url))
            return true;
        return false;
    }

    //Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable
    {
        Bitmap bitmap;
        PhotoToLoad photoToLoad;
        public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
        public void run()
        {
            if(imageViewReused(photoToLoad))
                return;
            if(bitmap!=null)
                photoToLoad.imageView.setImageBitmap(bitmap);
            else
                photoToLoad.imageView.setImageResource(stub_id);
        }
    }

    public void clearCache() {
        memoryCache.clear();
        fileCache.clear();
    }

}
</pre>
<p><strong>MemoryCache.java</strong></p>
<pre class="brush: java; title: MemoryCache.java; notranslate">package com.example.androidhive;

import java.lang.ref.SoftReference;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import android.graphics.Bitmap;

public class MemoryCache {
    private Map&amp;lt;String, SoftReference&amp;lt;Bitmap&amp;gt;&amp;gt; cache=Collections.synchronizedMap(new HashMap&amp;lt;String, SoftReference&amp;lt;Bitmap&amp;gt;&amp;gt;());

    public Bitmap get(String id){
        if(!cache.containsKey(id))
            return null;
        SoftReference&amp;lt;Bitmap&amp;gt; ref=cache.get(id);
        return ref.get();
    }

    public void put(String id, Bitmap bitmap){
        cache.put(id, new SoftReference&amp;lt;Bitmap&amp;gt;(bitmap));
    }

    public void clear() {
        cache.clear();
    }
}
</pre>
<p><strong>Utils.java</strong></p>
<pre class="brush: java; title: Utils.java; notranslate">package com.example.androidhive;

import java.io.InputStream;
import java.io.OutputStream;

public class Utils {
    public static void CopyStream(InputStream is, OutputStream os)
    {
        final int buffer_size=1024;
        try
        {
            byte[] bytes=new byte[buffer_size];
            for(;;)
            {
              int count=is.read(bytes, 0, buffer_size);
              if(count==-1)
                  break;
              os.write(bytes, 0, count);
            }
        }
        catch(Exception ex){}
    }
}
</pre>
<p><strong>FileCache.java</strong></p>
<pre class="brush: java; title: FileCache.java; notranslate">package com.example.androidhive;

import java.io.File;
import android.content.Context;

public class FileCache {

    private File cacheDir;

    public FileCache(Context context){
        //Find the dir to save cached images
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),&quot;LazyList&quot;);
        else
            cacheDir=context.getCacheDir();
        if(!cacheDir.exists())
            cacheDir.mkdirs();
    }

    public File getFile(String url){
        //I identify images by hashcode. Not a perfect solution, good for the demo.
        String filename=String.valueOf(url.hashCode());
        //Another possible solution (thanks to grantland)
        //String filename = URLEncoder.encode(url);
        File f = new File(cacheDir, filename);
        return f;

    }

    public void clear(){
        File[] files=cacheDir.listFiles();
        if(files==null)
            return;
        for(File f:files)
            f.delete();
    }

}
</pre>
<div style="display:none;">
This image for thumbnail purpose<br />
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/banner_custom_listview.png" alt="android custom listview" title="android custom listview" width="166" height="198" class="alignnone size-full wp-image-1445" />
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Android GridView Layout Tutorial</title>
		<link>http://www.androidhive.info/2012/02/android-gridview-layout-tutorial/</link>
		<comments>http://www.androidhive.info/2012/02/android-gridview-layout-tutorial/#comments</comments>
		<pubDate>Tue, 07 Feb 2012 10:48:33 +0000</pubDate>
		<dc:creator>Ravi Tamada</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Grid]]></category>
		<category><![CDATA[UI]]></category>

		<guid isPermaLink="false">http://www.androidhive.info/?p=1380</guid>
		<description><![CDATA[GridView layout in one of the most useful layouts in android. Gridview is mainly useful when we want show data in grid layout like displaying images or icons. This layout can be used to build applications like image viewer, audio ...]]></description>
			<content:encoded><![CDATA[<p>
GridView layout in one of the most useful layouts in android. Gridview is mainly useful when we want show data in grid layout like displaying images or icons. This layout can be used to build applications like image viewer, audio or video players in order to show elements in grid manner.</p>
<div class="downloadsection"><a href="http://download.androidhive.info/download?code=cgjtII6ZMOxYwGRgu4Q62MbRlMXx6LIKubwu1W3RF8ja1cbcpV40Hj5qQmwMKYdOatnuTJv9IZS0hc%3D7lqFuMybtyO1QbuUCuz2rpq720mEgVzMMj1" target="_blank"><img class="alignnone size-full wp-image-423" title="Download Code" src="http://www.androidhive.info/wp-content/uploads/2011/08/download_btn.png" alt="Download Code" width="173" height="41"></a></div>
<div class="downloadsection">
<iframe width="590" height="330" src="http://www.youtube.com/embed/JDjQ7nuXKIA" frameborder="0" allowfullscreen=""></iframe></div>
<h3>Basic GridView Layout</h3>
<p><strong>1</strong>. Create a new project by going to <strong>File ⇒ New Android Project</strong> and fill required details. (I named my main activity as <em>AndroidGridLayoutActivity.java</em>)<br />
<strong>2</strong>. Prepare your images which you want to show in grid layout and place them in <strong>res ⇒ drawable-hdpi</strong> folder.<br />
3. Create a new XML layout under layout and name it as <em>grid_layout.xml</em> <strong>(Right Click) layout ⇒ New ⇒ Android XML File</strong></p>
<pre class="brush: xml; title: grid_layout.xml; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;GridView xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:id=&quot;@+id/grid_view&quot;
    android:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot;
    android:numColumns=&quot;auto_fit&quot;
    android:columnWidth=&quot;90dp&quot;
    android:horizontalSpacing=&quot;10dp&quot;
    android:verticalSpacing=&quot;10dp&quot;
    android:gravity=&quot;center&quot;
    android:stretchMode=&quot;columnWidth&quot; &gt;  

&lt;/GridView&gt;
</pre>
<p><strong>4</strong>. Create a new Class by right clicking on <strong>(Right Click) src ⇒ package folder ⇒ New ⇒ Class</strong> and name your class as <em>ImageAdapter.java</em><br />
<strong>5</strong>. Extend your <strong>ImageAdapter.java</strong> class from <strong>BaseAdapter</strong> and fill it with following code.</p>
<pre class="brush: java; title: ImageAdapter.java; notranslate">
package com.example.androidhive;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class ImageAdapter extends BaseAdapter {
	private Context mContext;

	// Keep all Images in array
	public Integer[] mThumbIds = {
			R.drawable.pic_1, R.drawable.pic_2,
			R.drawable.pic_3, R.drawable.pic_4,
			R.drawable.pic_5, R.drawable.pic_6,
			R.drawable.pic_7, R.drawable.pic_8,
			R.drawable.pic_9, R.drawable.pic_10,
			R.drawable.pic_11, R.drawable.pic_12,
			R.drawable.pic_13, R.drawable.pic_14,
			R.drawable.pic_15
	};

	// Constructor
	public ImageAdapter(Context c){
		mContext = c;
	}

	@Override
	public int getCount() {
		return mThumbIds.length;
	}

	@Override
	public Object getItem(int position) {
		return mThumbIds[position];
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ImageView imageView = new ImageView(mContext);
        imageView.setImageResource(mThumbIds[position]);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
        return imageView;
	}

}
</pre>
<p><strong>6</strong>. Open your main activity class as shown below.</p>
<pre class="brush: java; title: AndroidGridLayoutActivity.java; notranslate" title="AndroidGridLayoutActivity.java">package com.example.androidhive;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

public class AndroidGridLayoutActivity extends Activity {

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

		GridView gridView = (GridView) findViewById(R.id.grid_view);

		// Instance of ImageAdapter Class
		gridView.setAdapter(new ImageAdapter(this));
	}
}
</pre>
<p>Run your project</p>
<div class="article-post-image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/output_gridview.png" alt="android grid view " title="android grid view " class="alignnone size-medium wp-image-1416" />
</div>
<p></p>
<h3>Showing selected grid image in new Activity (Full Screen)</h3>
<p>Until now we displayed all images in simple grid layout. To this we can add functionality like showing selected image in fullscreen. For this we need to pass image resource id from grid view to new activity.<br />
<strong>7</strong>. Create new XML file under layout folder and name it as <em>full_image.xml</em> and fill it following code.</p>
<pre class="brush: xml; title: full_image.xml; notranslate" title="full_image.xml">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" &gt;

    &lt;ImageView android:id="@+id/full_image_view"
        	android:layout_width="fill_parent"
        	android:layout_height="fill_parent"/&gt;

&lt;/LinearLayout&gt;
</pre>
<p><strong>8</strong>. Create a new Activity by right clicking on <strong>(Right Click) src ⇒ package folder ⇒ New ⇒ Class</strong> and name your class as <em>FullImageActivity.java</em> and type following code.</p>
<pre class="brush: java; title: FullImageActivity.java; notranslate" title="FullImageActivity.java">package com.example.androidhive;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;

public class FullImageActivity extends Activity {

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

		// get intent data
		Intent i = getIntent();

		// Selected image id
		int position = i.getExtras().getInt("id");
		ImageAdapter imageAdapter = new ImageAdapter(this);

		ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
		imageView.setImageResource(imageAdapter.mThumbIds[position]);
	}

}
</pre>
<p><strong>9</strong>. Modify your main activity class to following. I added click event for grid element.</p>
<pre class="brush: java; title: AndroidGridLayoutActivity.java; notranslate" title="AndroidGridLayoutActivity.java">package com.example.androidhive;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

public class AndroidGridLayoutActivity extends Activity {

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

		GridView gridView = (GridView) findViewById(R.id.grid_view);

		// Instance of ImageAdapter Class
		gridView.setAdapter(new ImageAdapter(this));

		/**
		 * On Click event for Single Gridview Item
		 * */
		gridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView&lt;?&gt; parent, View v,
					int position, long id) {

				// Sending image id to FullScreenActivity
				Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
				// passing array index
				i.putExtra("id", position);
				startActivity(i);
			}
		});
	}
}
</pre>
<p><strong>10</strong>. Open your <strong>AndroidManifest.xml</strong> and add entries of newly added activity.</p>
<pre class="brush: xml; title: AndroidManifest.xml; notranslate" title="AndroidManifest.xml">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidhive"
    android:versionCode="1"
    android:versionName="1.0" &gt;

    &lt;uses-sdk android:minSdkVersion="8" /&gt;

    &lt;application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" &gt;
        &lt;activity
            android:label="@string/app_name"
            android:name=".AndroidGridLayoutActivity" &gt;
            &lt;intent-filter &gt;
                &lt;action android:name="android.intent.action.MAIN" /&gt;

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

        &lt;!-- FullImageActivity --&gt;
        &lt;activity android:name=".FullImageActivity"&gt;&lt;/activity&gt;
    &lt;/application&gt;

&lt;/manifest&gt;
</pre>
<p>Finally run your project</p>
<div class="article-post-image">
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/output_gridview_singleview.png" alt="android grid view" title="android grid view" class="alignnone size-medium wp-image-1421" />
</div>
<div style="display:none;">
This image for thumbnail purpose<br />
<img src="http://www.androidhive.info/wp-content/uploads/2012/05/banner_gridview.png" alt="Android Gridview layout" title="Android Gridview layout" width="166" height="198" class="alignnone size-full wp-image-1446">
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.androidhive.info/2012/02/android-gridview-layout-tutorial/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

