<?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>Knowledge by Experience</title> <atom:link href="http://wptrafficanalyzer.in/blog/feed/" rel="self" type="application/rss+xml" /><link>http://wptrafficanalyzer.in/blog</link> <description></description> <lastBuildDate>Tue, 23 Jul 2019 09:25:05 +0000</lastBuildDate> <language>en-US</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.6.1</generator> <item><title>Storing Google Maps Android API V2 marker locations in MySQL</title><link>http://wptrafficanalyzer.in/blog/storing-google-maps-android-api-v2-marker-locations-in-mysql/</link> <comments>http://wptrafficanalyzer.in/blog/storing-google-maps-android-api-v2-marker-locations-in-mysql/#comments</comments> <pubDate>Mon, 14 Oct 2013 03:46:42 +0000</pubDate> <dc:creator>George Mathew</dc:creator> <category><![CDATA[Android]]></category> <category><![CDATA[Google Map Android API V2]]></category> <category><![CDATA[mysql]]></category> <category><![CDATA[SupportMapFragment]]></category><guid
isPermaLink="false">http://wptrafficanalyzer.in/blog/?p=8976</guid> <description><![CDATA[In this article, we will develop an Android application that stores user touched locations of Google Maps in a remote MySQL server. Since this application is developed using SupportMapFragment, it can support Android API version 8 and above. In order to send latitude and longitude from the application to the web server, we are using HTTPUrlConnection api in &#8220;POST&#8221; request method. Screenshot of this application is available towards the end of this article. This application is developed in Eclipse ( 4.2.0 ) with Android SDK ( 22.2.1 ) and ADT plugin ( 22.2.1 ) and is tested in Android API Level 2.3.6 and 4.1.2. 1. Create new Android application with the given below details Application Name : LocationMarkerMySQL Project Name : LocationMarkerMySQL Package Name : in.wptrafficanalyzer.locationmarkermysql Minimum Required SDK : API 8: Android 2.2 ( Froyo ) Target SDK : API 18: Android 4.3 Compile With: API 18: Android 4.3 Theme : Holo Light with Dark Action Bar 2. Download and configure Google Play Services Library in Eclipse Please follow the given below link to setup Google Play Service library in Eclipse. http://developer.android.com/google/play-services/setup.html 3. Referencing the Google Play Services library in this project Please follow the given below link to reference the [&#8230;]]]></description> <content:encoded><![CDATA[<p>In this article, we will develop an Android application that stores user touched locations of Google Maps in a remote MySQL server. Since this application is developed using <strong>SupportMapFragment</strong>, it can support Android API version 8 and above.</p><p>In order to send latitude and longitude from the application to the web server, we are using HTTPUrlConnection api in &#8220;POST&#8221; request method.</p><p><strong>Screenshot</strong> of this application is available towards the end of this article.</p><p>This application is developed in Eclipse ( 4.2.0 ) with Android SDK ( 22.2.1 ) and ADT plugin ( 22.2.1 ) and is tested in Android API Level 2.3.6 and 4.1.2.</p><p
style="text-align: center"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <ins
class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-0084597063187020"
data-ad-slot="4112080501"></ins><script>(adsbygoogle=window.adsbygoogle||[]).push({});</script></p><hr
/><p><strong>1. Create new Android application with the given below details</strong></p><p>Application Name : <strong>LocationMarkerMySQL</strong></p><p>Project Name : LocationMarkerMySQL</p><p>Package Name : in.wptrafficanalyzer.locationmarkermysql</p><p>Minimum Required SDK : API 8: Android 2.2 ( Froyo )</p><p>Target SDK : API 18: Android 4.3</p><p>Compile With: API 18: Android 4.3</p><p>Theme : Holo Light with Dark Action Bar</p><hr
/><p><strong>2. Download and configure Google Play Services Library in Eclipse</strong></p><p>Please follow the given below link to setup Google Play Service library in Eclipse.</p><p><a
title="http://developer.android.com/google/play-services/setup.html" href="http://developer.android.com/google/play-services/setup.html" target="_blank" rel="nofollow">http://developer.android.com/google/play-services/setup.html</a></p><hr
/><p><strong>3. Referencing the Google Play Services library in this project</strong></p><p>Please follow the given below link to reference the Google Play Service library into this project</p><p><a
title="http://developer.android.com/tools/projects/projects-eclipse.html#ReferencingLibraryProject" href="http://developer.android.com/tools/projects/projects-eclipse.html#ReferencingLibraryProject" target="_blank" rel="nofollow">http://developer.android.com/tools/projects/projects-eclipse.html#ReferencingLibraryProject</a></p><hr
/><p><strong>4. Get the API key for Google Maps Android API V2</strong></p><p>We need to get an API key from Google to use Google Maps in Android application.</p><p>Please follow the given below link to get the API key for Google Maps Android API v2.</p><p><a
title="https://developers.google.com/maps/documentation/android/start" href="https://developers.google.com/maps/documentation/android/start" target="_blank" rel="nofollow">https://developers.google.com/maps/documentation/android/start</a></p><hr
/><p><strong>5. Add Android Support Library ( V4 )  to this project</strong></p><p>By default, Android support library (android-support-v4.jar ) is added to this project by Eclipse IDE to the directory <strong><em>libs</em></strong>. If it is not added, we can do it manually by doing the following steps :</p><ul><li>Open Project Explorer by Clicking &#8220;Window -&gt; Show View -&gt; Project Explorer&#8221;</li><li>Right click this project</li><li>Then from popup menu, Click &#8220;Android Tools -&gt; Add Support Library &#8220;</li></ul><hr
/><p><strong>6. Update the file res/layout/activity_main.xml</strong></p><pre class="brush: xml; highlight: [11,12,13,14,15]; title: ; notranslate">
&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    android:paddingBottom=&quot;@dimen/activity_vertical_margin&quot;
    android:paddingLeft=&quot;@dimen/activity_horizontal_margin&quot;
    android:paddingRight=&quot;@dimen/activity_horizontal_margin&quot;
    android:paddingTop=&quot;@dimen/activity_vertical_margin&quot;
    ools:context=&quot;.MainActivity&quot; &gt;

    &lt;fragment
        android:id=&quot;@+id/map&quot;
        android:layout_width=&quot;fill_parent&quot;
        android:layout_height=&quot;fill_parent&quot;
        class=&quot;com.google.android.gms.maps.SupportMapFragment&quot; /&gt;

&lt;/RelativeLayout&gt;

</pre><hr
/><p><strong>7. Create a parser class namely MarkerJSONParser in the file src/in/wptrafficanalyzer/locationmarkermysql/MarkerJSONParser.java</strong></p><pre class="brush: java; highlight: [19,26,37,38,65,66]; title: ; notranslate">
package in.wptrafficanalyzer.locationmarkermysql;

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

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MarkerJSONParser {

    /** Receives a JSONObject and returns a list */
    public List&lt;HashMap&lt;String,String&gt;&gt; parse(JSONObject jObject){

        JSONArray jMarkers = null;
       try {
            /** Retrieves all the elements in the 'markers' array */
            jMarkers = jObject.getJSONArray(&quot;markers&quot;);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        /** Invoking getMarkers with the array of json object
        * where each json object represent a marker
        */
        return getMarkers(jMarkers);
    }

    private List&lt;HashMap&lt;String, String&gt;&gt; getMarkers(JSONArray jMarkers){
        int markersCount = jMarkers.length();
        List&lt;HashMap&lt;String, String&gt;&gt; markersList = new ArrayList&lt;HashMap&lt;String,String&gt;&gt;();
        HashMap&lt;String, String&gt; marker = null;

        /** Taking each marker, parses and adds to list object */
        for(int i=0; i&lt;markersCount;i++){
            try {
                /** Call getMarker with marker JSON object to parse the marker */
                marker = getMarker((JSONObject)jMarkers.get(i));
                markersList.add(marker);
            }catch (JSONException e){
                e.printStackTrace();
            }
        }
        return markersList;
    }

    /** Parsing the Marker JSON object */
    private HashMap&lt;String, String&gt; getMarker(JSONObject jMarker){

        HashMap&lt;String, String&gt; marker = new HashMap&lt;String, String&gt;();
        String lat = &quot;-NA-&quot;;
        String lng =&quot;-NA-&quot;;

        try {
            // Extracting latitude, if available
            if(!jMarker.isNull(&quot;lat&quot;)){
                lat = jMarker.getString(&quot;lat&quot;);
            }

            // Extracting longitude, if available
            if(!jMarker.isNull(&quot;lng&quot;)){
                lng = jMarker.getString(&quot;lng&quot;);
            }

            marker.put(&quot;lat&quot;, lat);
            marker.put(&quot;lng&quot;, lng);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return marker;
    }
}
</pre><hr
/><p><strong>8. Update the class &#8220;MainActivity&#8221; in the file src/in/wptrafficanalyzer/locationmarkermysql/MainActivity.java</strong></p><pre class="brush: java; highlight: [37,38,39,41,42,47,48,49,50,51,52,53,54,56,57,60,61,62,63,64,65,66,68,69,70,71,90,91,92,94,95,96,131,132,167,175,176]; title: ; notranslate">
package in.wptrafficanalyzer.locationmarkermysql;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends FragmentActivity {

    GoogleMap mGoogleMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Getting reference to SupportMapFragment
        SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);

        // Creating GoogleMap from SupportMapFragment
        mGoogleMap = fragment.getMap();

        // Enabling MyLocation button for the Google Map
        mGoogleMap.setMyLocationEnabled(true);

        // Setting OnClickEvent listener for the GoogleMap
        mGoogleMap.setOnMapClickListener(new OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latlng) {
                addMarker(latlng);
                sendToServer(latlng);
            }
        });

        // Starting locations retrieve task
        new RetrieveTask().execute();
    }

    // Adding marker on the GoogleMaps
    private void addMarker(LatLng latlng) {
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latlng);
        markerOptions.title(latlng.latitude + &quot;,&quot; + latlng.longitude);
        mGoogleMap.addMarker(markerOptions);
    }

    // Invoking background thread to store the touched location in Remove MySQL server
    private void sendToServer(LatLng latlng) {
        new SaveTask().execute(latlng);
    }
    // Background thread to save the location in remove MySQL server
    private class SaveTask extends AsyncTask&lt;LatLng, Void, Void&gt; {
        @Override
        protected Void doInBackground(LatLng... params) {
            String lat = Double.toString(params[0].latitude);
            String lng = Double.toString(params[0].longitude);
            String strUrl = &quot;http://192.168.1.3/location_marker_mysql/save.php&quot;;
            URL url = null;
            try {
                url = new URL(strUrl);

                HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
                connection.setRequestMethod(&quot;POST&quot;);
                connection.setDoOutput(true);
                OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
                connection.getOutputStream());

                outputStreamWriter.write(&quot;lat=&quot; + lat + &quot;&amp;lng=&quot;+lng);
                outputStreamWriter.flush();
                outputStreamWriter.close();

                InputStream iStream = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new
                InputStreamReader(iStream));

                StringBuffer sb = new StringBuffer();

                String line = &quot;&quot;;

                while( (line = reader.readLine()) != null){
                    sb.append(line);
                }

                reader.close();
                iStream.close();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }
    }

    // Background task to retrieve locations from remote mysql server
    private class RetrieveTask extends AsyncTask&lt;Void, Void, String&gt;{

        @Override
        protected String doInBackground(Void... params) {
            String strUrl = &quot;http://192.168.1.3/location_marker_mysql/retrieve.php&quot;;
            URL url = null;
            StringBuffer sb = new StringBuffer();
            try {
                url = new URL(strUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.connect();
                InputStream iStream = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
                String line = &quot;&quot;;
                while( (line = reader.readLine()) != null){
                    sb.append(line);
                }

                reader.close();
                iStream.close();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return sb.toString();
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            new ParserTask().execute(result);
        }
    }

    // Background thread to parse the JSON data retrieved from MySQL server
    private class ParserTask extends AsyncTask&lt;String, Void, List&lt;HashMap&lt;String, String&gt;&gt;&gt;{
        @Override
        protected List&lt;HashMap&lt;String,String&gt;&gt; doInBackground(String... params) {
            MarkerJSONParser markerParser = new MarkerJSONParser();
            JSONObject json = null;
            try {
                json = new JSONObject(params[0]);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            List&lt;HashMap&lt;String, String&gt;&gt; markersList = markerParser.parse(json);
            return markersList;
        }

        @Override
        protected void onPostExecute(List&lt;HashMap&lt;String, String&gt;&gt; result) {
            for(int i=0; i&lt;result.size();i++){
                HashMap&lt;String, String&gt; marker = result.get(i);
                LatLng latlng = new LatLng(Double.parseDouble(marker.get(&quot;lat&quot;)), Double.parseDouble(marker.get(&quot;lng&quot;)));
                addMarker(latlng);
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

</pre><hr
/><p><strong>9. Update the file AndroidManifest.xml</strong></p><pre class="brush: xml; highlight: [8,11,12,13,14,16,17,19,20,22,23,25,26,28,29,30,32,33,35,36,37,38,55,56,57]; title: ; 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;in.wptrafficanalyzer.locationmarkermysql&quot;
    android:versionCode=&quot;1&quot;
    android:versionName=&quot;1.0&quot; &gt;

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

    &lt;!-- Protect the map component of the application using application signature --&gt;
    &lt;permission
        android:name=&quot;in.wptrafficanalyzer.locationmarkermysql.permission.MAPS_RECEIVE&quot;
        android:protectionLevel=&quot;signature&quot; /&gt;

    &lt;!-- Allows to receive map --&gt;
    &lt;uses-permission android:name=&quot;in.wptrafficanalyzer.locationmarkermysql.permission.MAPS_RECEIVE&quot; /&gt;

    &lt;!-- Used by the Google Maps Android API V2 to download map tiles from Google Maps servers --&gt;
    &lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;

    &lt;!-- Allows the Google Maps Android API V2 to cache map tile data in the device's external storage area --&gt;
    &lt;uses-permission android:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot; /&gt;

    &lt;!-- Allows the Google Maps Android API V2 to use WiFi or mobile cell data (or both) to determine the device's location --&gt;
    &lt;uses-permission android:name=&quot;android.permission.ACCESS_COARSE_LOCATION&quot; /&gt;

    &lt;!-- Allows the Google Maps Android API V2 to use the Global Positioning System (GPS)
        to determine the device's location to within a very small area --&gt;
    &lt;uses-permission android:name=&quot;android.permission.ACCESS_FINE_LOCATION&quot; /&gt;

    &lt;!-- Allows to contact Google Serves --&gt;
    &lt;uses-permission android:name=&quot;com.google.android.providers.gsf.permission.READ_GSERVICES&quot; /&gt;

    &lt;!-- Google Maps Android API V2 requires OpenGL ES version 2 --&gt;
    &lt;uses-feature
        android:glEsVersion=&quot;0x00020000&quot;
        android:required=&quot;true&quot; /&gt;

    &lt;application
        android:allowBackup=&quot;true&quot;
        android:icon=&quot;@drawable/ic_launcher&quot;
        android:label=&quot;@string/app_name&quot;
        android:theme=&quot;@style/AppTheme&quot; &gt;
        &lt;activity
            android:name=&quot;in.wptrafficanalyzer.locationmarkermysql.MainActivity&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;!-- Specifies the Android API Key, which is obtained from Google API Console --&gt;
        &lt;meta-data
            android:name=&quot;com.google.android.maps.v2.API_KEY&quot;
            android:value=&quot;YOUR_ANDROID_API_KEY&quot; /&gt;

    &lt;/application&gt;
&lt;/manifest&gt;

</pre><hr
/><p
style="text-align: center"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <ins
class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-0084597063187020"
data-ad-slot="3824266707"></ins><script>(adsbygoogle=window.adsbygoogle||[]).push({});</script></p><hr
/><p><strong>10. Screenshot of the application</strong></p><div
id="attachment_8994" class="wp-caption aligncenter" style="width: 250px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/10/location_marker_mysql_screenshot.png"><img
class="size-full wp-image-8994" alt="Showing markers from MySQL server" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/10/location_marker_mysql_screenshot.png" width="240" height="320" /></a><p
class="wp-caption-text">Figure 1 : Showing markers from MySQL server</p></div><hr
/><p><strong>11. Source code of the php script file used in this demo application to store and retrieve locations from MySQL server</strong></p><div
class='w3eden'><div
class="wpdm-link-tpl link-btn light" data-durl="http://wptrafficanalyzer.in/blog/?wpdmdl=9378" ><div
class="media"><div
class="pull-left"><img
class="wpdm_icon" src="http://wptrafficanalyzer.in/blog/wp-content/plugins/download-manager/file-type-icons/zip.png" onError='this.src="http://wptrafficanalyzer.in/blog/wp-content/plugins/download-manager/file-type-icons/_blank.png";' /></div><div
class="media-body"><strong
class="ptitle">Storing Google Maps Android API V2 marker locations in MySQL - PHP <span
class="label label-default" style="font-weight: 400;">1.63 KB</span></strong><div><strong><a
class='wpdm-download-link wpdm-download-locked [btnclass]' rel='noindex nofollow' href='http://wptrafficanalyzer.in/blog/?wpdmdl=9378'><i
class=''></i>Download PHP Files</a></strong></div></div></div></div><div
style="clear: both"></div></div><hr
/><p><strong>12. Source code of this Android Application</strong></p><p
style="text-align: center"></p><div
class='w3eden'><div
class="wpdm-link-tpl link-btn light" data-durl="http://wptrafficanalyzer.in/blog/?wpdmdl=9379" ><div
class="media"><div
class="pull-left"><img
class="wpdm_icon" src="http://wptrafficanalyzer.in/blog/wp-content/plugins/download-manager/file-type-icons/zip.png" onError='this.src="http://wptrafficanalyzer.in/blog/wp-content/plugins/download-manager/file-type-icons/_blank.png";' /></div><div
class="media-body"><strong
class="ptitle">Storing Google Maps Android API V2 marker locations in MySQL <span
class="label label-default" style="font-weight: 400;">535.25 KB</span></strong><div><strong><a
class='wpdm-download-link wpdm-download-locked [btnclass]' rel='noindex nofollow' href='http://wptrafficanalyzer.in/blog/?wpdmdl=9379'><i
class=''></i>Download Full Source Code</a></strong></div></div></div></div><div
style="clear: both"></div></div><hr
/><div><b>How to hire me?</b><br
/><img
style='float:left;padding:10px' src='http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/george_wpta.jpg'><p>I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in<br
/><br
/>You can hire me on hourly basis or on project basis for Android applications development.<br
/><br
/>For hiring me, please mail your requirements to info@wptrafficanalyzer.in.<br
/></p><p><i><u>My other blogs</u></i><br
/><a
href='http://store4js.blogspot.com/' rel='nofollow' target='_blank'>store4js.blogspot.com</a></p><hr
/><p
style='clear:both'></p></div>]]></content:encoded> <wfw:commentRss>http://wptrafficanalyzer.in/blog/storing-google-maps-android-api-v2-marker-locations-in-mysql/feed/</wfw:commentRss> <slash:comments>24</slash:comments> </item> <item><title>Android Sidebar Navigation Drawer with Icons</title><link>http://wptrafficanalyzer.in/blog/android-sidebar-navigation-drawer-with-icons/</link> <comments>http://wptrafficanalyzer.in/blog/android-sidebar-navigation-drawer-with-icons/#comments</comments> <pubDate>Wed, 09 Oct 2013 16:05:09 +0000</pubDate> <dc:creator>George Mathew</dc:creator> <category><![CDATA[Android]]></category> <category><![CDATA[actionbarcompat]]></category> <category><![CDATA[navigation drawer]]></category><guid
isPermaLink="false">http://wptrafficanalyzer.in/blog/?p=8892</guid> <description><![CDATA[In this article, we will see how to develop an Android application containing sidebar navigation drawer menu with icons and counter. Here count specifies, how many times the drawer menu item is selected by the user since the application is opened. In order to display ActionBar in legacy Android versions, we are making use ActionBarCompat library ( V7 ) . For navigation drawer library, we are making use Android Support Library ( V4 ) . This application is developed in Eclipse 4.2.0 with Android SDK ( 22.2.1 ) and ADT plugin ( 22.2.1 ). Screenshot of this application is available towards the end of this article. 1. Create an Android application project with the given below details Application Name : NavigationDrawerLegacy Project Name : NavigationDrawerLegacy Package Name : in.wptrafficanalyzer.navigationdrawerlegacy Minimum Required SDK : API 8 : Android 2.2 ( Froyo ) Target SDK : API 18 : Android 4.3 Compile With : API 18 : Android 4.3 Theme : Holo Light with Dark Action Bar 2. Adding Android Support Library ( V4 )  By default, Android support library (android-support-v4.jar ) is added by Eclipse IDE to the directory libs. If it is not added, we can do it manually by doing the following [&#8230;]]]></description> <content:encoded><![CDATA[<p>In this article, we will see how to develop an Android application containing sidebar navigation drawer menu with icons and counter. Here count specifies, how many times the drawer menu item is selected by the user since the application is opened.</p><p
style="text-align: center"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <ins
class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-0084597063187020"
data-ad-slot="4112080501"></ins><script>(adsbygoogle=window.adsbygoogle||[]).push({});</script></p><p>In order to display ActionBar in legacy Android versions, we are making use <strong>ActionBarCompat</strong> library ( V7 ) . For navigation drawer library, we are making use Android Support Library ( V4 ) .</p><p>This application is developed in Eclipse 4.2.0 with Android SDK ( 22.2.1 ) and ADT plugin ( 22.2.1 ).</p><p>Screenshot of this application is available towards the end of this article.</p><hr
/><p><strong>1. Create an Android application project with the given below details</strong></p><ul><li>Application Name : NavigationDrawerLegacy</li></ul><ul><li>Project Name : NavigationDrawerLegacy</li></ul><ul><li>Package Name : in.wptrafficanalyzer.navigationdrawerlegacy</li></ul><ul><li>Minimum Required SDK : API 8 : Android 2.2 ( Froyo )</li></ul><ul><li>Target SDK : API 18 : Android 4.3</li></ul><ul><li>Compile With : API 18 : Android 4.3</li></ul><ul><li>Theme : Holo Light with Dark Action Bar</li></ul><hr
/><p><strong>2. Adding Android Support Library ( V4 ) </strong></p><p>By default, Android support library (android-support-v4.jar ) is added by Eclipse IDE to the directory <strong><em>libs</em></strong>. If it is not added, we can do it manually by doing the following steps :</p><ul><li>Open Project Explorer by Clicking &#8220;Window -&gt; Show View -&gt; Project Explorer&#8221;</li><li>Right click this project</li><li>Then from popup menu, Click &#8220;Android Tools -&gt; Add Support Library &#8220;</li></ul><hr
/><p><strong>3. Adding ActionBarCompat Support Library ( V7 ) </strong></p><p>Please refer the article titled &#8220;<a
title="Android - Setting up ActionBarCompat support library in Eclipse" href="http://wptrafficanalyzer.in/blog/android-setting-up-actionbarcompat-support-library-in-eclipse" target="_blank" rel="nofollow">Android &#8211; Setting up ActionBarCompat support library in Eclipse</a>&#8221;</p><hr
/><p><strong>4. Link this project to ActionBarCompat library</strong></p><div
id="attachment_8900" class="wp-caption aligncenter" style="width: 360px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/10/navigation_drawer_legacy_link_v7.png"><img
class="size-full wp-image-8900" alt="Link this project to ActionBarCompat library ( V7)" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/10/navigation_drawer_legacy_link_v7.png" width="350" height="336" /></a><p
class="wp-caption-text">Figure 1 : Link this project to ActionBarCompat library ( V7)</p></div><hr
/><p><strong>5. Download and extract the icon images to the directory res/drawable-mdpi</strong></p><p><a
title="Icon Images" href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2012/06/flag_images.zip" target="_blank" rel="nofollow">Icon Images</a></p><hr
/><p><strong>6. Update the file res/values/strings.xml</strong></p><pre class="brush: xml; highlight: [12,13,14,15,16,17,18,19,20,21,22,23]; title: ; 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;NavigationDrawerLegacy&lt;/string&gt;
    &lt;string name=&quot;action_settings&quot;&gt;Settings&lt;/string&gt;
    &lt;string name=&quot;hello_world&quot;&gt;Hello world!&lt;/string&gt;
    &lt;string name=&quot;hello&quot;&gt;Hello&lt;/string&gt;
    &lt;dimen name=&quot;count&quot;&gt;10dp&lt;/dimen&gt;
    &lt;string name=&quot;drawer_open&quot;&gt;Open navigation drawer&lt;/string&gt;
    &lt;string name=&quot;drawer_close&quot;&gt;Close navigation drawer&lt;/string&gt;

    &lt;string-array name=&quot;countries&quot;&gt;
        &lt;item&gt;India&lt;/item&gt;
        &lt;item&gt;Pakistan&lt;/item&gt;
        &lt;item&gt;Sri Lanka&lt;/item&gt;
        &lt;item&gt;China&lt;/item&gt;
        &lt;item&gt;Bangladesh&lt;/item&gt;
        &lt;item&gt;Nepal&lt;/item&gt;
        &lt;item&gt;Afghanistan&lt;/item&gt;
        &lt;item&gt;North Korea&lt;/item&gt;
        &lt;item&gt;South Korea&lt;/item&gt;
        &lt;item&gt;Japan&lt;/item&gt;
    &lt;/string-array&gt;

&lt;/resources&gt;
</pre><hr
/><p><strong>7. Create a Shape drawable in the file res/drawable/counter_shape.xml</strong></p><pre class="brush: xml; highlight: [5,6,7,8]; title: ; notranslate">

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;shape xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; &gt;
    &lt;solid android:color=&quot;#EAEAEA&quot;/&gt;

    &lt;corners android:bottomLeftRadius=&quot;20dp&quot;
        android:topRightRadius=&quot;20dp&quot;
        android:topLeftRadius=&quot;20dp&quot;
        android:bottomRightRadius=&quot;20dp&quot; /&gt;

&lt;/shape&gt;

</pre><hr
/><p><strong>8. Create a Shape drawable in the file res/drawable/drawer_title_shape.xml</strong></p><pre class="brush: xml; highlight: [5,6,7,8]; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;shape xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; &gt;
    &lt;solid android:color=&quot;#EAEAEA&quot;/&gt;

    &lt;corners android:bottomLeftRadius=&quot;0dp&quot;
        android:topRightRadius=&quot;0dp&quot;
        android:topLeftRadius=&quot;0dp&quot;
        android:bottomRightRadius=&quot;0dp&quot; /&gt;
&lt;/shape&gt;
</pre><hr
/><p><strong>9. Create a layout for the navigation drawer listview for legacy Android Versions ( API Level &lt; 11 ) in the file res/layout/drawer_layout.xml</strong></p><pre class="brush: xml; highlight: [6,7,8,9,10,11,12,13,14,15,16,18,19,20,21,22,23,24,26,27,28,29,30,31,32,33,34,35,36]; title: ; 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;60dp&quot; &gt;

    &lt;ImageView
        android:id=&quot;@+id/flag&quot;
        android:layout_width=&quot;40dp&quot;
        android:layout_height=&quot;40dp&quot;
        android:paddingLeft=&quot;10dp&quot;
        android:paddingTop=&quot;10dp&quot;
        android:paddingRight=&quot;10dp&quot;
        android:paddingBottom=&quot;10dp&quot;
        android:layout_alignParentLeft=&quot;true&quot;
        android:layout_centerVertical=&quot;true&quot;
        android:contentDescription=&quot;@string/hello&quot; /&gt;

    &lt;TextView
        android:id=&quot;@+id/country&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_toRightOf=&quot;@id/flag&quot;
        android:layout_centerVertical=&quot;true&quot;
        android:textSize=&quot;15sp&quot; /&gt;

    &lt;TextView
        android:id=&quot;@+id/count&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_marginRight=&quot;@dimen/count&quot;
        android:layout_alignParentRight=&quot;true&quot;
        android:layout_centerVertical=&quot;true&quot;
        android:gravity=&quot;center&quot;
        android:padding=&quot;0dp&quot;
        android:background=&quot;@drawable/counter_shape&quot;
        android:textSize=&quot;15sp&quot; /&gt;

&lt;/RelativeLayout&gt;

</pre><hr
/><p><strong>10. Create a layout for the navigation drawer listview for Android Versions ( API Level &gt;= 11 ) in the file res/layout-v11/drawer_layout.xml </strong></p><pre class="brush: xml; highlight: [4,7,8,9,10,11,12,13,14,15,16,17,19,20,21,22,23,24,25,27,28,29,30,31,32,33,34,35,36,37]; title: ; 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:background=&quot;?android:attr/activatedBackgroundIndicator&quot;
    android:layout_height=&quot;60dp&quot; &gt;

    &lt;ImageView
        android:id=&quot;@+id/flag&quot;
        android:layout_width=&quot;40dp&quot;
        android:layout_height=&quot;40dp&quot;
        android:paddingLeft=&quot;10dp&quot;
        android:paddingTop=&quot;10dp&quot;
        android:paddingRight=&quot;10dp&quot;
        android:paddingBottom=&quot;10dp&quot;
        android:layout_alignParentLeft=&quot;true&quot;
        android:layout_centerVertical=&quot;true&quot;
        android:contentDescription=&quot;@string/hello&quot; /&gt;

    &lt;TextView
        android:id=&quot;@+id/country&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_toRightOf=&quot;@id/flag&quot;
        android:layout_centerVertical=&quot;true&quot;
        android:textSize=&quot;15sp&quot; /&gt;

    &lt;TextView
        android:id=&quot;@+id/count&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_marginRight=&quot;@dimen/count&quot;
        android:layout_alignParentRight=&quot;true&quot;
        android:layout_centerVertical=&quot;true&quot;
        android:gravity=&quot;center&quot;
        android:padding=&quot;0dp&quot;
        android:background=&quot;@drawable/counter_shape&quot;
        android:textSize=&quot;15sp&quot; /&gt;

&lt;/RelativeLayout&gt;

</pre><hr
/><p><strong>11. Create a layout file namely res/layout/fragment_layout.xml for the fragment CountryFragment</strong></p><pre class="brush: xml; highlight: [7,8,9,10,11,12]; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    android:orientation=&quot;vertical&quot; &gt;

    &lt;TextView
        android:id=&quot;@+id/tv_content&quot;
        android:layout_width=&quot;fill_parent&quot;
        android:layout_height=&quot;fill_parent&quot;
        android:gravity=&quot;center&quot;
        android:textSize=&quot;40sp&quot; /&gt;

&lt;/LinearLayout&gt;
</pre><hr
/><p><strong>1</strong><strong>2. Update the layout file res/layout/activity_main.xml to include navigation drawer in the MainActivity</strong></p><pre class="brush: xml; highlight: [7,8,9,10,19,20,21,22,23,24,25,27,28,29,30,31,32,33,34]; title: ; notranslate">
&lt;android.support.v4.widget.DrawerLayout
    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:id=&quot;@+id/drawer_layout&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot; &gt;
    &lt;!-- The main content view --&gt;
    &lt;FrameLayout
        android:id=&quot;@+id/content_frame&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;match_parent&quot; /&gt;
    &lt;!-- The navigation drawer --&gt;
    &lt;LinearLayout
        android:id=&quot;@+id/drawer&quot;
        android:layout_width=&quot;240dp&quot;
        android:layout_height=&quot;match_parent&quot;
        android:orientation=&quot;vertical&quot;
        android:layout_gravity=&quot;start&quot; &gt;

        &lt;TextView
            android:layout_width=&quot;match_parent&quot;
            android:layout_height=&quot;50dp&quot;
            android:gravity=&quot;center&quot;
            android:textSize=&quot;20sp&quot;
            android:text=&quot;Country&quot;
            android:background=&quot;@drawable/drawer_title_shape&quot; /&gt;

        &lt;ListView android:id=&quot;@+id/drawer_list&quot;
            android:layout_width=&quot;match_parent&quot;
            android:layout_height=&quot;match_parent&quot;
            android:choiceMode=&quot;singleChoice&quot;
            android:divider=&quot;@android:color/darker_gray&quot;
            android:dividerHeight=&quot;0.1dp&quot;
            android:textColor=&quot;@android:color/white&quot;
            android:background=&quot;#fff&quot; /&gt;

    &lt;/LinearLayout&gt;
&lt;/android.support.v4.widget.DrawerLayout&gt;

</pre><hr
/><p><strong>13. Create a fragment class namely CountryFragment in the file src/in/wptrafficanalyzer/navigationdrawerlegacy/CountryFragment.java</strong></p><pre class="brush: java; highlight: [28,29]; title: ; notranslate">

package in.wptrafficanalyzer.navigationdrawerlegacy;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class CountryFragment extends Fragment{

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

        // Retrieving the currently selected item number
        int position = getArguments().getInt(&quot;position&quot;);

        // List of rivers
        String[] countries = getResources().getStringArray(R.array.countries);

        // Creating view correspoding to the fragment
        View v = inflater.inflate(R.layout.fragment_layout, container, false);

        // Getting reference to the TextView of the Fragment
        TextView tv = (TextView) v.findViewById(R.id.tv_content);

        // Setting currently selected river name in the TextView
        tv.setText(countries[position]);

        return v;
    }
}

</pre><hr
/><p><strong><br
/> 14. Update the file src/in/wptrafficanalyzer/navigationdrawerlegacy/MainActivity.java</strong></p><pre class="brush: java; highlight: [28,29,31,32,33,34,35,36,37,38,39,40,41,42,43,45,46,47,48,65,66,71,72,74,75,77,78,79,80,81,82,83,84,85,87,88,90,91,93,94,95,97,98,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,126,127,129,130,133,135,136,145,146,181,210,211,219]; title: ; notranslate">

package in.wptrafficanalyzer.navigationdrawerlegacy;

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

import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

 int mPosition = -1;
 String mTitle = &quot;&quot;;

 // Array of strings storing country names
 String[] mCountries ;

 // Array of integers points to images stored in /res/drawable-ldpi/
 int[] mFlags = new int[]{
 R.drawable.india,
 R.drawable.pakistan,
 R.drawable.srilanka,
 R.drawable.china,
 R.drawable.bangladesh,
 R.drawable.nepal,
 R.drawable.afghanistan,
 R.drawable.nkorea,
 R.drawable.skorea,
 R.drawable.japan
 };

// Array of strings to initial counts
 String[] mCount = new String[]{
 &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;,
 &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot; };

 private DrawerLayout mDrawerLayout;
 private ListView mDrawerList;
 private ActionBarDrawerToggle mDrawerToggle;
 private LinearLayout mDrawer ;
 private List&lt;HashMap&lt;String,String&gt;&gt; mList ;
 private SimpleAdapter mAdapter;
 final private String COUNTRY = &quot;country&quot;;
 final private String FLAG = &quot;flag&quot;;
 final private String COUNT = &quot;count&quot;;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

 // Getting an array of country names
 mCountries = getResources().getStringArray(R.array.countries);

 // Title of the activity
 mTitle = (String)getTitle();

 // Getting a reference to the drawer listview
 mDrawerList = (ListView) findViewById(R.id.drawer_list);

 // Getting a reference to the sidebar drawer ( Title + ListView )
 mDrawer = ( LinearLayout) findViewById(R.id.drawer);

 // Each row in the list stores country name, count and flag
 mList = new ArrayList&lt;HashMap&lt;String,String&gt;&gt;();
 for(int i=0;i&lt;10;i++){
 HashMap&lt;String, String&gt; hm = new HashMap&lt;String,String&gt;();
 hm.put(COUNTRY, mCountries[i]);
 hm.put(COUNT, mCount[i]);
 hm.put(FLAG, Integer.toString(mFlags[i]) );
 mList.add(hm);
 }

// Keys used in Hashmap
 String[] from = { FLAG,COUNTRY,COUNT };

// Ids of views in listview_layout
 int[] to = { R.id.flag , R.id.country , R.id.count};

// Instantiating an adapter to store each items
 // R.layout.drawer_layout defines the layout of each item
 mAdapter = new SimpleAdapter(this, mList, R.layout.drawer_layout, from, to);

 // Getting reference to DrawerLayout
 mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);

 // Creating a ToggleButton for NavigationDrawer with drawer event listener
 mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer , R.string.drawer_open,R.string.drawer_close){

 /** Called when drawer is closed */
 public void onDrawerClosed(View view) {
 highlightSelectedCountry();
 supportInvalidateOptionsMenu();
 }

/** Called when a drawer is opened */
 public void onDrawerOpened(View drawerView) {
 getSupportActionBar().setTitle(&quot;Select a Country&quot;);
 supportInvalidateOptionsMenu();
 }
 };

 // Setting event listener for the drawer
 mDrawerLayout.setDrawerListener(mDrawerToggle);

 // ItemClick event handler for the drawer items
 mDrawerList.setOnItemClickListener(new OnItemClickListener() {

@Override
 public void onItemClick(AdapterView&lt;?&gt; arg0, View arg1, int position,
 long arg3) {

 // Increment hit count of the drawer list item
 incrementHitCount(position);

 if(position &lt; 5) { // Show fragment for countries : 0 to 4
 showFragment(position);
 }else{ // Show message box for countries : 5 to 9
 Toast.makeText(getApplicationContext(), mCountries[position], Toast.LENGTH_LONG).show();
 }

 // Closing the drawer
 mDrawerLayout.closeDrawer(mDrawer);
 }
 });

 // Enabling Up navigation
 getSupportActionBar().setDisplayHomeAsUpEnabled(true);

 getSupportActionBar().setDisplayShowHomeEnabled(true);

// Setting the adapter to the listView
 mDrawerList.setAdapter(mAdapter);

 }

 @Override
 protected void onPostCreate(Bundle savedInstanceState) {
 super.onPostCreate(savedInstanceState);
 mDrawerToggle.syncState();

 }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
 if (mDrawerToggle.onOptionsItemSelected(item)) {
 return true;
 }
 return super.onOptionsItemSelected(item);
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
 // Inflate the menu; this adds items to the action bar if it is present.
 getMenuInflater().inflate(R.menu.main, menu);
 return true;
 }

 public void incrementHitCount(int position){
 HashMap&lt;String, String&gt; item = mList.get(position);
 String count = item.get(COUNT);
 item.remove(COUNT);
 if(count.equals(&quot;&quot;)){
 count = &quot; 1 &quot;;
 }else{
 int cnt = Integer.parseInt(count.trim());
 cnt ++;
 count = &quot; &quot; + cnt + &quot; &quot;;
 }
 item.put(COUNT, count);
 mAdapter.notifyDataSetChanged();
 }

 public void showFragment(int position){

 //Currently selected country
 mTitle = mCountries[position];

// Creating a fragment object
 CountryFragment cFragment = new CountryFragment();

// Creating a Bundle object
 Bundle data = new Bundle();

// Setting the index of the currently selected item of mDrawerList
 data.putInt(&quot;position&quot;, position);

// Setting the position to the fragment
 cFragment.setArguments(data);

// Getting reference to the FragmentManager
 FragmentManager fragmentManager = getSupportFragmentManager();

// Creating a fragment transaction
 FragmentTransaction ft = fragmentManager.beginTransaction();

// Adding a fragment to the fragment transaction
 ft.replace(R.id.content_frame, cFragment);

// Committing the transaction
 ft.commit();
 }

 // Highlight the selected country : 0 to 4
 public void highlightSelectedCountry(){
 int selectedItem = mDrawerList.getCheckedItemPosition();

 if(selectedItem &gt; 4)
 mDrawerList.setItemChecked(mPosition, true);
 else
 mPosition = selectedItem;

 if(mPosition!=-1)
 getSupportActionBar().setTitle(mCountries[mPosition]);
 }
}

</pre><hr
/><p><strong><br
/> 15. Update the file AndroidManifest.xml</strong></p><pre class="brush: xml; highlight: [15]; title: ; 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;in.wptrafficanalyzer.navigationdrawerlegacy&quot;
    android:versionCode=&quot;1&quot;
    android:versionName=&quot;1.0&quot; &gt;

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

    &lt;application
        android:allowBackup=&quot;true&quot;
        android:icon=&quot;@drawable/ic_launcher&quot;
        android:label=&quot;@string/app_name&quot;
        android:theme=&quot;@style/Theme.AppCompat.Light&quot; &gt;
        &lt;activity
            android:name=&quot;in.wptrafficanalyzer.navigationdrawerlegacy.MainActivity&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;/application&gt;

&lt;/manifest&gt;
</pre><hr
/><p
style="text-align: center"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <ins
class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-0084597063187020"
data-ad-slot="3824266707"></ins><script>(adsbygoogle=window.adsbygoogle||[]).push({});</script></p><hr
/><p><strong>16. Screenshot of the application</strong></p><div
id="attachment_8933" class="wp-caption aligncenter" style="width: 358px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/10/navigation_drawer_legacy_screenshot.png"><img
class="size-full wp-image-8933 " title="Sidebar Navigation Drawer Demo" alt="Sidebar Navigation Drawer Demo" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/10/navigation_drawer_legacy_screenshot.png" width="348" height="534" /></a><p
class="wp-caption-text">Figure 2 : Sidebar Navigation Drawer Demo</p></div><hr
/><p><strong>17. Download Source Code</strong></p><p
style="text-align: center"></p><div
class='w3eden'><div
class="wpdm-link-tpl link-btn light" data-durl="http://wptrafficanalyzer.in/blog/?wpdmdl=9377" ><div
class="media"><div
class="pull-left"><img
class="wpdm_icon" src="http://wptrafficanalyzer.in/blog/wp-content/plugins/download-manager/file-type-icons/zip.png" onError='this.src="http://wptrafficanalyzer.in/blog/wp-content/plugins/download-manager/file-type-icons/_blank.png";' /></div><div
class="media-body"><strong
class="ptitle">Android Sidebar Navigation Drawer with Icons and count <span
class="label label-default" style="font-weight: 400;">596.95 KB</span></strong><div><strong><a
class='wpdm-download-link wpdm-download-locked [btnclass]' rel='noindex nofollow' href='http://wptrafficanalyzer.in/blog/?wpdmdl=9377'><i
class=''></i>Download Full Source Code</a></strong></div></div></div></div><div
style="clear: both"></div></div><hr
/><div><b>How to hire me?</b><br
/><img
style='float:left;padding:10px' src='http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/george_wpta.jpg'><p>I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in<br
/><br
/>You can hire me on hourly basis or on project basis for Android applications development.<br
/><br
/>For hiring me, please mail your requirements to info@wptrafficanalyzer.in.<br
/></p><p><i><u>My other blogs</u></i><br
/><a
href='http://store4js.blogspot.com/' rel='nofollow' target='_blank'>store4js.blogspot.com</a></p><hr
/><p
style='clear:both'></p></div>]]></content:encoded> <wfw:commentRss>http://wptrafficanalyzer.in/blog/android-sidebar-navigation-drawer-with-icons/feed/</wfw:commentRss> <slash:comments>37</slash:comments> </item> <item><title>Android Sending and Receiving data from remote server using IntentService</title><link>http://wptrafficanalyzer.in/blog/android-sending-and-receiving-data-from-remote-server-using-intentservice/</link> <comments>http://wptrafficanalyzer.in/blog/android-sending-and-receiving-data-from-remote-server-using-intentservice/#comments</comments> <pubDate>Thu, 26 Sep 2013 12:07:10 +0000</pubDate> <dc:creator>George Mathew</dc:creator> <category><![CDATA[Android]]></category> <category><![CDATA[BroadcastReceiver]]></category> <category><![CDATA[IntentService]]></category><guid
isPermaLink="false">http://wptrafficanalyzer.in/blog/?p=8854</guid> <description><![CDATA[In this article, we will see how to develop an Android application that sends and receives data from a web server using IntentService. IntentService provides a simple mechanism to execute long lasting operations ( eg : downloading data )  in a background thread. In this application user is able to select a country from a spinner widget and on selecting the country, corresponding capital name will be fetched from an http web server using IntentService and displayed to the user. Major steps involved in this application are as follows : Populate Spinner widget with a String ArrayAdapter Create an IntentService class ( CapitalService ), which will be invoked when user selects a country from the Spinner widget Override the method &#8220;onHandleIntent()&#8221; of the IntentService class to fetch the capital of the selected country from a remote server Define a BroadcastReceiver class ( CapitalReceiver) in MainActivity, to receive the broadcast message send from the IntentService class Override the method &#8220;onReceive()&#8221; of the BroadcastReceiver class to receive data from service and set in TextView of the MainActivity Register the broadcast receiver in MainActivity with Android&#8217;s LocalBroadcastManager This application is developed in Eclipse 4.2.0 with Android SDK ( 22.2.1 ) and ADT plugin ( 22.2.1 [&#8230;]]]></description> <content:encoded><![CDATA[<p>In this article, we will see how to develop an Android application that sends and receives data from a web server using IntentService. IntentService provides a simple mechanism to execute long lasting operations ( eg : downloading data )  in a background thread.</p><p>In this application user is able to select a country from a spinner widget and on selecting the country, corresponding capital name will be fetched from an http web server using IntentService and displayed to the user.</p><p
style="text-align: center"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <ins
class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-0084597063187020"
data-ad-slot="4112080501"></ins><script>(adsbygoogle=window.adsbygoogle||[]).push({});</script></p><p>Major steps involved in this application are as follows :</p><ul><li>Populate Spinner widget with a String ArrayAdapter</li></ul><ul><li>Create an IntentService class ( CapitalService ), which will be invoked when user selects a country from the Spinner widget</li></ul><ul><li>Override the method &#8220;onHandleIntent()&#8221; of the IntentService class to fetch the capital of the selected country from a remote server</li></ul><ul><li>Define a BroadcastReceiver class ( CapitalReceiver) in MainActivity, to receive the broadcast message send from the IntentService class</li></ul><ul><li>Override the method &#8220;onReceive()&#8221; of the BroadcastReceiver class to receive data from service and set in TextView of the MainActivity</li></ul><ul><li>Register the broadcast receiver in MainActivity with Android&#8217;s LocalBroadcastManager</li></ul><p>This application is developed in Eclipse 4.2.0 with Android SDK ( 22.2.1 ) and ADT plugin ( 22.2.1 )</p><hr
/><p><strong>1. Create an Android application project with the given below project details</strong></p><ul><li>Application Name : IntentServiceDemo</li></ul><ul><li>Project Name : IntentServiceDemo</li></ul><ul><li>Package Name : in.wptrafficanalyzer.intentservicedemo</li></ul><ul><li>Minimum Required SDK : API 8 : Android 2.2 ( Froyo )</li></ul><ul><li>Target SDK : API 18 : Android 4.3</li></ul><ul><li>Compile With : API 18 : Android 4.3</li></ul><ul><li>Theme : Holo Light with Dark Action Bar</li></ul><hr
/><p><strong>2.  Update the layout file res/layout/activity_main.xml for the MainActivity</strong></p><pre class="brush: xml; highlight: [11,12,13,14,15]; title: ; notranslate">

&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    android:paddingBottom=&quot;@dimen/activity_vertical_margin&quot;
    android:paddingLeft=&quot;@dimen/activity_horizontal_margin&quot;
    android:paddingRight=&quot;@dimen/activity_horizontal_margin&quot;
    android:paddingTop=&quot;@dimen/activity_vertical_margin&quot;
    tools:context=&quot;.MainActivity&quot; &gt;

    &lt;Spinner
        android:id=&quot;@+id/spr_country&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_centerHorizontal=&quot;true&quot; /&gt;

    &lt;TextView
        android:id=&quot;@+id/tv_capital&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_below=&quot;@id/spr_country&quot;
        android:layout_centerHorizontal=&quot;true&quot; /&gt;

&lt;/RelativeLayout&gt;

</pre><hr
/><p><strong>3. Creating a layout for the Spinner Items in the file res/layout/spinner_layout.xml</strong></p><pre class="brush: xml; highlight: [2,3,4,5,6,7]; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;&lt;/pre&gt;
&lt;TextView 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:id=&quot;@+id/tv_item&quot;
    android:padding=&quot;15dp&quot;
    android:textColor=&quot;@android:color/black&quot; &gt;

&lt;/TextView&gt;

</pre><hr
/><p><strong>4. Creating a class called Constants to define application constants in the file src/in/wptrafficanalyzer/intentservicedemo/Constants.java</strong></p><pre class="brush: java; highlight: [6,7,8,9,10,11,12,13]; title: ; notranslate">
package in.wptrafficanalyzer.intentservicedemo;

public final class Constants {

    // Action Name to IntentFilter
    public static final String BROADCAST_ACTION = &quot;in.wptrafficanalyzer.intentservicedemo.BROADCAST&quot;;

    public static final String EXTRA_COUNTRY = &quot;country&quot;;

    public static final String EXTRA_CAPITAL = &quot;capital&quot;;

    // The url to the server where php script for capital is available
    public static final String SERVER_URL = &quot;http://wptrafficanalyzer.in/p/intent_service_demo&quot;;

}

</pre><hr
/><p><strong>5. Creating an IntentService class called CapitalService in the file <strong>src/in/wptrafficanalyzer/intentservicedemo/</strong>CapitalService.java</strong></p><pre class="brush: java; highlight: [47,48,49,50,51,52,53,54,55,56,57,72,73,74,75,76,85,86,87,88]; title: ; notranslate">
package in.wptrafficanalyzer.intentservicedemo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import android.app.IntentService;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

public class CapitalService extends IntentService{

    public CapitalService(){
        super(&quot;Empty Constructor&quot;);
    }

    public CapitalService(String name) {
        super(name);
        // TODO Auto-generated constructor stub
    }

    // This method is executed in background when this service is started
    @Override
    protected void onHandleIntent(Intent intent) {
        String country = &quot;&quot;;
        String capital = &quot;&quot;;
        String url = &quot;&quot;;

        try {

            country = URLEncoder.encode(intent.getStringExtra(Constants.EXTRA_COUNTRY),&quot;utf-8&quot;);

        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        url = Constants.SERVER_URL + &quot;/get_capital.php?country=&quot; + country;

        try {
            // Retreiving capital from the url
            capital = downloadUrl(url);

            // Creating an intent for broadcastreceiver
            Intent broadcastIntent = new Intent(Constants.BROADCAST_ACTION);

            // Attaching data to the intent
            broadcastIntent.putExtra(Constants.EXTRA_CAPITAL, capital);

            // Sending the broadcast
            LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(broadcastIntent);

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

    /** A method to download data from url */
    private String downloadUrl(String strUrl) throws IOException{
        String data = &quot;&quot;;
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try{
            URL url = new URL(strUrl);
            // Creating an http connection to communicate with url
            urlConnection = (HttpURLConnection) url.openConnection();

            // Connecting to url
            urlConnection.connect();

            // Reading data from url
            iStream = urlConnection.getInputStream();

            bufferedReader br = new BufferedReader(new InputStreamReader(iStream));

            StringBuffer sb = new StringBuffer();

            String line = &quot;&quot;;
            while( ( line = br.readLine()) != null){
                sb.append(line);
            }

            data = sb.toString();

            br.close();

        }catch(Exception e){
            Log.d(&quot;Exception while fetching data&quot;, e.toString());
        }finally{
            iStream.close();
            urlConnection.disconnect();
        }
        return data;
    }
}
</pre><hr
/><p><strong>6. Updating the class MainActivity in the file <strong>src/in/wptrafficanalyzer/intentservicedemo/</strong>MainActivity.java</strong></p><pre class="brush: java; highlight: [67,68,69,70,71,87,88,99,100,101,102,103,104,105,106]; title: ; notranslate">
package in.wptrafficanalyzer.intentservicedemo;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class MainActivity extends Activity {

    // Array of countries
    String[] mCountry = new String[] {
            &quot;India&quot;,
            &quot;Pakistan&quot;,
            &quot;Bangladesh&quot;,
            &quot;Srilanka&quot;,
            &quot;Nepal&quot;,
            &quot;China&quot;,
            &quot;Japan&quot;,
            &quot;South Korea&quot;,
            &quot;North Korea&quot;,
            &quot;Afghanistan&quot;
    };

    Spinner mSprCountry;
    TextView mTvCapital;
    ArrayAdapter&lt;String&gt; mAdapter;
    Intent mServiceIntent;
    CapitalReceiver mReceiver;
    IntentFilter mFilter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Adapter for Country Spinner
        mAdapter = new ArrayAdapter&lt;String&gt;(getApplicationContext(),R.layout.spinner_layout, mCountry);

        // Getting reference to TextView
        mTvCapital = (TextView) findViewById(R.id.tv_capital);

        // Getting reference to Country Spinner
        mSprCountry = (Spinner) findViewById(R.id.spr_country);

        // Setting adapter for the Country Spinner
        mSprCountry.setAdapter(mAdapter);

        // Creating an intent service
        mServiceIntent = new Intent(getApplicationContext(), CapitalService.class);

        mSprCountry.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView&lt;?&gt; arg0, View arg1,
                int arg2, long arg3) {
                if(arg1!=null){
                    String country = ((TextView)arg1).getText().toString();
                    mServiceIntent.putExtra(Constants.EXTRA_COUNTRY, country);

                    // Starting the CapitalService to fetch the capital of the country
                    startService(mServiceIntent);
                }
            }

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

        // Instantiating BroadcastReceiver
        mReceiver = new CapitalReceiver();

        // Creating an IntentFilter with action
        mFilter = new IntentFilter(Constants.BROADCAST_ACTION);

         // Registering BroadcastReceiver with this activity for the intent filter
         LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(mReceiver, mFilter);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    // Defining a BroadcastReceiver
    private class CapitalReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            String capital = intent.getStringExtra(Constants.EXTRA_CAPITAL);
            mTvCapital.setText(&quot;Capital : &quot; + capital);
        }
    }
}
</pre><hr
/><p><strong>7. Create a php script file namely &#8220;get_capital.php&#8221; in a web server having php support</strong></p><pre class="brush: php; highlight: [19,20]; title: ; notranslate">
&lt;?php
    $country = &quot;none&quot;;
    $capital = array(
        &quot;India&quot;=&gt;&quot;New Delhi&quot;,
        &quot;Pakistan&quot;=&gt;&quot;Islamabad&quot;,
        &quot;Bangladesh&quot;=&gt;&quot;Dhaka&quot;,
        &quot;Srilanka&quot;=&gt;&quot;Colombo&quot;,
        &quot;Nepal&quot;=&gt;&quot;Kathmandu&quot;,
        &quot;China&quot;=&gt;&quot;Beijing&quot;,
        &quot;Japan&quot;=&gt;&quot;Tokyo&quot;,
        &quot;South Korea&quot;=&gt;&quot;Seoul&quot;,
        &quot;North Korea&quot;=&gt;&quot;Pyongyang&quot;,
        &quot;Afghanistan&quot;=&gt;&quot;Kabul&quot;,
    );
    if(isset($_GET['country'])){
        $country = $_GET['country'];
    }

    if(array_key_exists($country,$capital))
        echo $capital[$country];
    else
        echo &quot;Please pass a valid 'country' param from this list : &quot; . implode(&quot;,&quot;,array_keys($capital));

</pre><p>Note : After creating this file, please ensure that, the variable<strong> <em>SERVER_URL</em></strong> of the class<strong> <em>Constants</em><em> </em></strong>is updated with your server url.</p><hr
/><p
style="text-align: center"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <ins
class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-0084597063187020"
data-ad-slot="3824266707"></ins><script>(adsbygoogle=window.adsbygoogle||[]).push({});</script></p><hr
/><p><strong>8. Screenshot of the application</strong></p><div
id="attachment_8883" class="wp-caption aligncenter" style="width: 360px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/09/intent_service_demo_screenshot.png"><img
class="size-full wp-image-8883" alt="Selecting a country from the Spinner" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/09/intent_service_demo_screenshot.png" width="350" height="541" /></a><p
class="wp-caption-text">Selecting a country from the Spinner</p></div><hr
/><p><strong>9. Download the source code of the application</strong></p><p
style="text-align: center"></p><div
class='w3eden'><div
class="wpdm-link-tpl link-btn light" data-durl="http://wptrafficanalyzer.in/blog/?wpdmdl=9376" ><div
class="media"><div
class="pull-left"><img
class="wpdm_icon" src="http://wptrafficanalyzer.in/blog/wp-content/plugins/download-manager/file-type-icons/zip.png" onError='this.src="http://wptrafficanalyzer.in/blog/wp-content/plugins/download-manager/file-type-icons/_blank.png";' /></div><div
class="media-body"><strong
class="ptitle">Android Sending and Receiving data from remote server using IntentService <span
class="label label-default" style="font-weight: 400;">515.71 KB</span></strong><div><strong><a
class='wpdm-download-link wpdm-download-locked [btnclass]' rel='noindex nofollow' href='http://wptrafficanalyzer.in/blog/?wpdmdl=9376'><i
class=''></i>Download Full Source Code</a></strong></div></div></div></div><div
style="clear: both"></div></div><hr
/><div><b>How to hire me?</b><br
/><img
style='float:left;padding:10px' src='http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/george_wpta.jpg'><p>I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in<br
/><br
/>You can hire me on hourly basis or on project basis for Android applications development.<br
/><br
/>For hiring me, please mail your requirements to info@wptrafficanalyzer.in.<br
/></p><p><i><u>My other blogs</u></i><br
/><a
href='http://store4js.blogspot.com/' rel='nofollow' target='_blank'>store4js.blogspot.com</a></p><hr
/><p
style='clear:both'></p></div>]]></content:encoded> <wfw:commentRss>http://wptrafficanalyzer.in/blog/android-sending-and-receiving-data-from-remote-server-using-intentservice/feed/</wfw:commentRss> <slash:comments>5</slash:comments> </item> <item><title>Swipable Navigation Tabs using ActionBarCompat library</title><link>http://wptrafficanalyzer.in/blog/swipable-navigation-tabs-using-actionbarcompat-library/</link> <comments>http://wptrafficanalyzer.in/blog/swipable-navigation-tabs-using-actionbarcompat-library/#comments</comments> <pubDate>Thu, 29 Aug 2013 06:39:43 +0000</pubDate> <dc:creator>George Mathew</dc:creator> <category><![CDATA[Android]]></category><guid
isPermaLink="false">http://wptrafficanalyzer.in/blog/?p=8784</guid> <description><![CDATA[In this article, we will see how to develop an Android application containing swipable navigation tabs. In order to enable swiping between tabs, we are making use ViewPager in this application. This application is developed in Eclipse ( 4.2.0 ) with Android SDK ( 22.0.5 ) and ADT plugin ( 22.0.5 ) . 1. Create new Android application project namely &#8220;ActionBarCompatNavTabSwipe&#8221; 2. Configure the application 3. Design application launcher icon 4. Create a blank activity 5. Enter MainActivity Details 6. Update the file res/values/strings.xml 7. Create a layout file for Fragment1 in the file res/layout/fragment1.xml 8. Create a layout file for Fragment2 in the file res/layout/fragment2.xml 9. Update the layout file res/layout/activity_main.xml 10. Create a class Fragment1 in the file src/in/wptrafficanalyzer/actionbarcompatnavtabswipe/Fragment1.java 11. Create a class Fragment2 in the file src/in/wptrafficanalyzer/actionbarcompatnavtabswipe/Fragment2.java 12. Create a class MyFragmentPagerAdapter in the file src/in/wptrafficanalyzer/actionbarcompatnavtabswipe/MyFragmentPagerAdapter.java 13. Update the class MainActivity in the file src/in/wptrafficanalyzer/actionbarcompatnavtabswipe/MainActivity.java 14. Update the configuration file AndroidManifest.xml 15. Screenshot of the application 16. Download Source Code How to hire me?I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.inYou can hire me on hourly basis or on project basis for Android applications development.For hiring me, please mail your requirements to info@wptrafficanalyzer.in.My other [&#8230;]]]></description> <content:encoded><![CDATA[<p>In this article, we will see how to develop an Android application containing <strong>swipable</strong> navigation <strong>tabs</strong>.</p><p>In order to enable swiping between tabs, we are making use <strong>ViewPager</strong> in this application.</p><p>This application is developed in Eclipse ( 4.2.0 ) with Android SDK ( 22.0.5 ) and ADT plugin ( 22.0.5 ) .</p><p
style="text-align: center"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <ins
class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-0084597063187020"
data-ad-slot="4112080501"></ins><script>(adsbygoogle=window.adsbygoogle||[]).push({});</script></p><hr
/><p><strong>1. Create new Android application project namely &#8220;ActionBarCompatNavTabSwipe&#8221;</strong></p><div
id="attachment_8788" class="wp-caption aligncenter" style="width: 460px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/08/actionbarcompat_navtab_swipe_new_android.png"><img
class="size-full wp-image-8788" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/08/actionbarcompat_navtab_swipe_new_android.png" alt="Create new Android application project" width="450" height="447" /></a><p
class="wp-caption-text">Figure 1 : Create new Android application project</p></div><hr
/><p><strong>2. Configure the application</strong></p><div
id="attachment_8789" class="wp-caption aligncenter" style="width: 460px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/08/actionbarcompat_navtab_swipe_configure.png"><img
class="size-full wp-image-8789" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/08/actionbarcompat_navtab_swipe_configure.png" alt="Configure the application project" width="450" height="447" /></a><p
class="wp-caption-text">Figure 2 : Configure the application project</p></div><hr
/><p><strong>3. Design application launcher icon</strong></p><div
id="attachment_8790" class="wp-caption aligncenter" style="width: 460px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/08/actionbarcompat_navtab_swipe_icon.png"><img
class="size-full wp-image-8790" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/08/actionbarcompat_navtab_swipe_icon.png" alt="Design application launcher icon" width="450" height="423" /></a><p
class="wp-caption-text">Figure 3 : Design application launcher icon</p></div><hr
/><p><strong>4. Create a blank activity</strong></p><div
id="attachment_8791" class="wp-caption aligncenter" style="width: 460px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/08/actionbarcompat_navtab_swipe_blank.png"><img
class="size-full wp-image-8791" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/08/actionbarcompat_navtab_swipe_blank.png" alt="Create a blank activity" width="450" height="423" /></a><p
class="wp-caption-text">Figure 4 : Create a blank activity</p></div><hr
/><p><strong>5. Enter MainActivity Details</strong></p><div
id="attachment_8792" class="wp-caption aligncenter" style="width: 460px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/08/actionbarcompat_navtab_swipe_main.png"><img
class="size-full wp-image-8792" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/08/actionbarcompat_navtab_swipe_main.png" alt="Enter MainActivity details" width="450" height="423" /></a><p
class="wp-caption-text">Figure 5 : Enter MainActivity details</p></div><hr
/><p><strong>6. Update the file res/values/strings.xml</strong></p><pre class="brush: xml; highlight: [6,7,8]; title: ; 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;ActionBarCompatNavTabSwipe&lt;/string&gt;
    &lt;string name=&quot;action_settings&quot;&gt;Settings&lt;/string&gt;
    &lt;string name=&quot;hello_world&quot;&gt;Hello world!&lt;/string&gt;
    &lt;string name=&quot;fragment1&quot;&gt;Fragment1&lt;/string&gt;
    &lt;string name=&quot;fragment2&quot;&gt;Fragment2&lt;/string&gt;
&lt;/resources&gt;

</pre><hr
/><p><strong>7. Create a layout file for Fragment1 in the file res/layout/fragment1.xml</strong></p><pre class="brush: xml; highlight: [6,7,8,9,10]; title: ; 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; &gt;

    &lt;TextView
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_centerInParent=&quot;true&quot;
        android:text=&quot;@string/fragment1&quot; /&gt;

&lt;/RelativeLayout&gt;

</pre><hr
/><p><strong>8. Create a layout file for Fragment2 in the file res/layout/fragment2.xml</strong></p><pre class="brush: xml; highlight: [6,7,8,9,10]; title: ; 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; &gt;

    &lt;TextView
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_centerInParent=&quot;true&quot;
        android:text=&quot;@string/fragment2&quot; /&gt;

&lt;/RelativeLayout&gt;

</pre><hr
/><p><strong>9. Update the layout file res/layout/activity_main.xml</strong></p><pre class="brush: xml; highlight: [6,7,8,9]; title: ; notranslate">
&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot; &gt;

    &lt;android.support.v4.view.ViewPager
        android:id=&quot;@+id/pager&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot; /&gt;

&lt;/RelativeLayout&gt;

</pre><hr
/><p><strong>10. Create a class Fragment1 in the file src/in/wptrafficanalyzer/actionbarcompatnavtabswipe/Fragment1.java</strong></p><pre class="brush: java; highlight: [15]; title: ; notranslate">

package in.wptrafficanalyzer.actionbarcompatnavtabswipe;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragment1 extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment1, null);
    }
}

</pre><hr
/><p><strong>11. Create a class Fragment2 in the file src/in/wptrafficanalyzer/actionbarcompatnavtabswipe/Fragment2.java</strong></p><pre class="brush: java; highlight: [16]; title: ; notranslate">

package in.wptrafficanalyzer.actionbarcompatnavtabswipe;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragment2 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment2, null);
    }
}

</pre><hr
/><p><strong>12. Create a class MyFragmentPagerAdapter in the file src/in/wptrafficanalyzer/actionbarcompatnavtabswipe/MyFragmentPagerAdapter.java</strong></p><pre class="brush: java; highlight: [25,26,30,31]; title: ; notranslate">
package in.wptrafficanalyzer.actionbarcompatnavtabswipe;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class MyFragmentPagerAdapter extends FragmentPagerAdapter{

    final int PAGE_COUNT = 2;

    /** Constructor of the class */
    public MyFragmentPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    /** This method will be invoked when a page is requested to create */
    @Override
    public Fragment getItem(int arg0) {
        Bundle data = new Bundle();
        switch(arg0){

            /** tab1 is selected */
            case 0:
                Fragment1 fragment1 = new Fragment1();
                return fragment1;

            /** tab2 is selected */
            case 1:
                Fragment2 fragment2 = new Fragment2();
                return fragment2;
        }
        return null;
    }

    /** Returns the number of pages */
    @Override
    public int getCount() {
        return PAGE_COUNT;
    }
}

</pre><hr
/><p><strong>13. Update the class MainActivity in the file src/in/wptrafficanalyzer/actionbarcompatnavtabswipe/MainActivity.java</strong></p><pre class="brush: java; highlight: [22,23,25,26,43,44,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69]; title: ; notranslate">

package in.wptrafficanalyzer.actionbarcompatnavtabswipe;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.Tab;
import android.support.v7.app.ActionBarActivity;

public class MainActivity extends ActionBarActivity {

    private ViewPager mPager;

    ActionBar mActionbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /** Getting a reference to action bar of this activity */
        mActionbar = getSupportActionBar();

        /** Set tab navigation mode */
        mActionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        /** Getting a reference to ViewPager from the layout */
        mPager = (ViewPager) findViewById(R.id.pager);

        /** Getting a reference to FragmentManager */
        FragmentManager fm = getSupportFragmentManager();

        /** Defining a listener for pageChange */
        ViewPager.SimpleOnPageChangeListener pageChangeListener = new ViewPager.SimpleOnPageChangeListener(){
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                mActionbar.setSelectedNavigationItem(position);
            }
        };

        /** Setting the pageChange listener to the viewPager */
        mPager.setOnPageChangeListener(pageChangeListener);

        /** Creating an instance of FragmentPagerAdapter */
        MyFragmentPagerAdapter fragmentPagerAdapter = new MyFragmentPagerAdapter(fm);

        /** Setting the FragmentPagerAdapter object to the viewPager object */
        mPager.setAdapter(fragmentPagerAdapter);

        mActionbar.setDisplayShowTitleEnabled(true);

        /** Defining tab listener */
        ActionBar.TabListener tabListener = new ActionBar.TabListener() {

            @Override
            public void onTabUnselected(Tab tab, FragmentTransaction ft) {
            }

            @Override
            public void onTabSelected(Tab tab, FragmentTransaction ft) {
                mPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabReselected(Tab tab, FragmentTransaction ft) {
            }
        };

        /** Creating fragment1 Tab */
        Tab tab = mActionbar.newTab()
            .setText(&quot;Tab1&quot;)
            .setTabListener(tabListener);

        mActionbar.addTab(tab);

        /** Creating fragment2 Tab */
        tab = mActionbar.newTab()
            .setText(&quot;Tab2&quot;)
            .setTabListener(tabListener);

        mActionbar.addTab(tab);
    }
}

</pre><hr
/><p><strong>14. Update the configuration file AndroidManifest.xml</strong></p><pre class="brush: xml; highlight: [15]; title: ; 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;in.wptrafficanalyzer.actionbarcompatnavtabswipe&quot;
    android:versionCode=&quot;1&quot;
    android:versionName=&quot;1.0&quot; &gt;

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

    &lt;application
        android:allowBackup=&quot;true&quot;
        android:icon=&quot;@drawable/ic_launcher&quot;
        android:label=&quot;@string/app_name&quot;
        android:theme=&quot;@style/Theme.AppCompat&quot; &gt;
        &lt;activity
            android:name=&quot;in.wptrafficanalyzer.actionbarcompatnavtabswipe.MainActivity&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;/application&gt;
&lt;/manifest&gt;

</pre><hr
/><p
style="text-align: center"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <ins
class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-0084597063187020"
data-ad-slot="3824266707"></ins><script>(adsbygoogle=window.adsbygoogle||[]).push({});</script></p><hr
/><p><strong>15. Screenshot of the application</strong></p><div
id="attachment_8810" class="wp-caption aligncenter" style="width: 452px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/08/actionbarcompat_navtab_swipe_screenshot.png"><img
class="size-full wp-image-8810" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/08/actionbarcompat_navtab_swipe_screenshot.png" alt="Screenshot of the application" width="442" height="718" /></a><p
class="wp-caption-text">Figure 6 : Screenshot of the application</p></div><hr
/><p><strong>16. Download Source Code</strong></p><p
style="text-align: center"></p><div
class='w3eden'><div
class="wpdm-link-tpl link-btn light" data-durl="http://wptrafficanalyzer.in/blog/?wpdmdl=9375" ><div
class="media"><div
class="pull-left"><img
class="wpdm_icon" src="http://wptrafficanalyzer.in/blog/wp-content/plugins/download-manager/file-type-icons/zip.png" onError='this.src="http://wptrafficanalyzer.in/blog/wp-content/plugins/download-manager/file-type-icons/_blank.png";' /></div><div
class="media-body"><strong
class="ptitle">Swipable Navigation Tabs using ActionBarCompat library <span
class="label label-default" style="font-weight: 400;">574.95 KB</span></strong><div><strong><a
class='wpdm-download-link wpdm-download-locked [btnclass]' rel='noindex nofollow' href='http://wptrafficanalyzer.in/blog/?wpdmdl=9375'><i
class=''></i>Download Full Source Code</a></strong></div></div></div></div><div
style="clear: both"></div></div><hr
/><div><b>How to hire me?</b><br
/><img
style='float:left;padding:10px' src='http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/george_wpta.jpg'><p>I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in<br
/><br
/>You can hire me on hourly basis or on project basis for Android applications development.<br
/><br
/>For hiring me, please mail your requirements to info@wptrafficanalyzer.in.<br
/></p><p><i><u>My other blogs</u></i><br
/><a
href='http://store4js.blogspot.com/' rel='nofollow' target='_blank'>store4js.blogspot.com</a></p><hr
/><p
style='clear:both'></p></div>]]></content:encoded> <wfw:commentRss>http://wptrafficanalyzer.in/blog/swipable-navigation-tabs-using-actionbarcompat-library/feed/</wfw:commentRss> <slash:comments>3</slash:comments> </item> <item><title>Android SearchView Widget with ActionBarCompat library</title><link>http://wptrafficanalyzer.in/blog/android-searchview-widget-with-actionbarcompat-library/</link> <comments>http://wptrafficanalyzer.in/blog/android-searchview-widget-with-actionbarcompat-library/#comments</comments> <pubDate>Tue, 06 Aug 2013 08:44:45 +0000</pubDate> <dc:creator>George Mathew</dc:creator> <category><![CDATA[Android]]></category> <category><![CDATA[actionbarcompat]]></category> <category><![CDATA[content provider]]></category> <category><![CDATA[Google Map Android API V2]]></category> <category><![CDATA[loader]]></category> <category><![CDATA[search]]></category> <category><![CDATA[searchview widget]]></category><guid
isPermaLink="false">http://wptrafficanalyzer.in/blog/?p=8681</guid> <description><![CDATA[In this article we will develop an Android application that demonstrates how to create a searchview widget in action bar using ActionBarCompat library. This application facilitates users to search places using Google Places API. As user types in place name in searchview, places that matches the typed in characters will be listed as suggestions. On selecting an item from the suggestion, the corresponding place will be shown in the Google Maps Android API V2. We need following for this application : ActionBarCompat library : We know that, SearchView widget is only available since Android API Level 11 and its previous versions does not have the SearchView widget. In order for the backward compatibility, we can use ActionBarCompat library which is available with Android Support library revision 18. Google Play Services Library : Since we are using Google Maps Android API V2 with this application, we need Google Play Service library for this application to work. Configuration file for SearchView widget : This configuration file is used to configure the searchview widget. For this application, this file is available at res/xml/searchable.xml Searchable Activity : An activity that handles the search requests from searchview widget. In this application, MainActivity acts as the [&#8230;]]]></description> <content:encoded><![CDATA[<p>In this article we will develop an Android application that demonstrates how to create a searchview widget in action bar using ActionBarCompat library.</p><p>This application facilitates users to search places using Google Places API. As user types in place name in searchview, places that matches the typed in characters will be listed as suggestions. On selecting an item from the suggestion, the corresponding place will be shown in the Google Maps Android API V2.</p><p
style="text-align: center"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <ins
class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-0084597063187020"
data-ad-slot="4112080501"></ins><script>(adsbygoogle=window.adsbygoogle||[]).push({});</script></p><p>We need following for this application :</p><p><strong>ActionBarCompat library</strong> : We know that, SearchView widget is only available since Android API Level 11 and its previous versions does not have the SearchView widget. In order for the backward compatibility, we can use ActionBarCompat library which is available with Android Support library revision 18.</p><p><strong>Google Play Services Library : </strong>Since we are using Google Maps Android API V2 with this application, we need Google Play Service library for this application to work.</p><p><strong>Configuration file for SearchView widget</strong> : This configuration file is used to configure the searchview widget. For this application, this file is available at res/xml/searchable.xml</p><p><strong>Searchable Activity </strong>: An activity that handles the search requests from searchview widget. In this application, MainActivity acts as the searchable activity.</p><p><strong>Content Provider </strong>: The searchview widget performs the search operation on the data provided by the content provider.</p><p><strong>Loaders </strong>: Loaders are used to execute tasks in background ( non-ui thread ) . We are using two loaders in the MainActivity class. One loader is used in the method doSearch() which is invoked when user presses the &#8220;Go&#8221; button of the soft keyboard. The second loader is used in the method &#8220;getPlace()&#8221;, which is invoked when an item in the search suggestion list is selected.</p><p><strong>Activity Style </strong>: The activity that implements the action bar should apply the style <strong>Theme.AppCompat </strong>or <strong>Theme.AppCompat.Light</strong>  or <strong>Theme.AppCompat.DarkActionBar. </strong> This can be done in AndroidManifest.xml file.<strong></strong></p><p
style="text-align: center"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <ins
class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-0084597063187020"
data-ad-slot="3824266707"></ins><script>(adsbygoogle=window.adsbygoogle||[]).push({});</script></p><p>This application is developed in Eclipse 4.2.0 with ADT plugin 22.0.5, Android Support library 18 and Google Play Service library 9.</p><p>Please jump to end of this article to see the screenshots of this application.</p><hr
/><p><strong>1. Create new Android application project namely &#8220;LocationActionBarCompatSearchViewV2&#8243;</strong></p><div
id="attachment_8690" class="wp-caption aligncenter" style="width: 460px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/08/actionbarcompat_searchview_v2_new.png"><img
class="size-full wp-image-8690" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/08/actionbarcompat_searchview_v2_new.png" alt="Create new Android application project" width="450" height="450" /></a><p
class="wp-caption-text">Figure 1 : Create new Android application project</p></div><hr
/><p><strong>2. Configure the application</strong></p><div
id="attachment_8691" class="wp-caption aligncenter" style="width: 460px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/08/actionbarcompat_searchview_v2_configure.png"><img
class="size-full wp-image-8691" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/08/actionbarcompat_searchview_v2_configure.png" alt="Configure the application project" width="450" height="450" /></a><p
class="wp-caption-text">Figure 2 : Configure the application project</p></div><hr
/><p><strong>3. Design application launcher icon</strong></p><div
id="attachment_8692" class="wp-caption aligncenter" style="width: 460px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/08/location_actionbarcompat_searchview_icon.png"><img
class="size-full wp-image-8692" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/08/location_actionbarcompat_searchview_icon.png" alt="Design application launcher icon" width="450" height="423" /></a><p
class="wp-caption-text">Figure 3 : Design application launcher icon</p></div><hr
/><p><strong>4. Create a blank activity</strong></p><div
id="attachment_8693" class="wp-caption aligncenter" style="width: 460px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/08/location_actionbarcompat_searchview_blank.png"><img
class="size-full wp-image-8693" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/08/location_actionbarcompat_searchview_blank.png" alt="Create a blank activity" width="450" height="423" /></a><p
class="wp-caption-text">Figure 4 : Create a blank activity</p></div><hr
/><p><strong>5. Enter MainActivity details</strong></p><div
id="attachment_8695" class="wp-caption aligncenter" style="width: 460px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/08/location_actionbarcompat_searchview_main.png"><img
class="size-full wp-image-8695" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/08/location_actionbarcompat_searchview_main.png" alt="Enter MainActivity Details" width="450" height="423" /></a><p
class="wp-caption-text">Figure 5 : Enter MainActivity Details</p></div><hr
/><p><strong> 6. Setup ActionBarCompat library in Eclipse IDE</strong></p><p>Please refer the article titled &#8220;<a
title="Android - Setting up ActionBarCompat support library in Eclipse" href="http://wptrafficanalyzer.in/blog/android-setting-up-actionbarcompat-support-library-in-eclipse" rel="nofollow" target="_blank">Android &#8211; Setting up ActionBarCompat support library in Eclipse</a>&#8221;</p><hr
/><p><strong>7. Download and configure Google Play Services Library in Eclipse</strong></p><p>Please follow the given below link to setup Google Play Service library in Eclipse.</p><p><a
title="http://developer.android.com/google/play-services/setup.html" href="http://developer.android.com/google/play-services/setup.html" rel="nofollow" target="_blank">http://developer.android.com/google/play-services/setup.html</a></p><hr
/><p><strong>8. Link this project to ActionBarCompat library and Google Play Service llibrary</strong></p><div
id="attachment_8697" class="wp-caption aligncenter" style="width: 460px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/08/location_actionbarcompat_linking.png"><img
class="size-full wp-image-8697" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/08/location_actionbarcompat_linking.png" alt="Linking this application with Google Play Services library and Action Bar Compat library" width="450" height="549" /></a><p
class="wp-caption-text">Figure 6 : Linking this application with Google Play Services library and Action Bar Compat library</p></div><hr
/><p><strong>9. Get the API key for Google Maps Android API V2</strong></p><p>We need to get an API key from Google to use Google Maps in Android application.</p><p>Please follow the given below link to get the API key for Google Maps Android API v2.</p><p><a
href="https://developers.google.com/maps/documentation/android/start" rel="nofollow" target="_blank">https://developers.google.com/maps/documentation/android/start</a></p><hr
/><p><strong>10. Get the API key for Google Places API</strong></p><p>We can create API key for Google Place API by clicking &#8220;Create new Browser key&#8221;  available at the &#8220;API Access&#8221; pane of the Google console URL : <a
title="http://code.google.com/apis/console" href="http://code.google.com/apis/console" rel="nofollow" target="_blank">http://code.google.com/apis/console</a>.</p><p>Also ensure that, &#8220;<strong>Places API</strong>&#8221; is enabled in the &#8220;Services&#8221; pane of the Google console.</p><hr
/><p><strong>11. Update the file res/values/strings.xml</strong></p><pre class="brush: xml; highlight: [7,8,9]; title: ; 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;SearchViewWithActionBarCompat&lt;/string&gt;
    &lt;string name=&quot;action_settings&quot;&gt;Settings&lt;/string&gt;
    &lt;string name=&quot;hello_world&quot;&gt;Hello world!&lt;/string&gt;
    &lt;string name=&quot;action_search&quot;&gt;Search&lt;/string&gt;
    &lt;string name=&quot;search_hint&quot;&gt;Search Places&lt;/string&gt;
    &lt;string name=&quot;search_settings&quot;&gt;Search Places&lt;/string&gt;

&lt;/resources&gt;

</pre><hr
/><p><strong>12. Update the layout file res/layout/activity_main.xml</strong></p><pre class="brush: xml; highlight: [7,8,9,10]; title: ; notranslate">

&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    tools:context=&quot;.MainActivity&quot; &gt;

    &lt;fragment
        android:id=&quot;@+id/map&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot; /&gt;

&lt;/RelativeLayout&gt;

</pre><hr
/><p><strong>13. Update the menu file res/menu/main.xml</strong></p><pre class="brush: xml; highlight: [2,8,9]; title: ; notranslate">
&lt;menu xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:myapp=&quot;http://schemas.android.com/apk/res-auto&quot; &gt;

    &lt;item
        android:id=&quot;@+id/action_search&quot;
        android:orderInCategory=&quot;100&quot;
        android:title=&quot;@string/action_search&quot;
        myapp:actionViewClass=&quot;android.support.v7.widget.SearchView&quot;
        myapp:showAsAction=&quot;always&quot; /&gt;

    &lt;item
        android:id=&quot;@+id/action_settings&quot;
        android:orderInCategory=&quot;100&quot;
        android:showAsAction=&quot;never&quot;
        android:title=&quot;@string/action_settings&quot;/&gt;

&lt;/menu&gt;

</pre><hr
/><p><strong>14. Create the class file src/in/wptrafficanalyzer/locationactionbarcompatsearchviewv2/PlaceJSONParser.java</strong></p><pre class="brush: java; highlight: [18,19,37,38,39,64,65,66]; title: ; notranslate">
package in.wptrafficanalyzer.locationactionbarcompatsearchviewv2;

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

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class PlaceJSONParser {

    /** Receives a JSONObject and returns a list */
    public List&lt;HashMap&lt;String,String&gt;&gt; parse(JSONObject jObject){

        JSONArray jPlaces = null;
        try {
            /** Retrieves all the elements in the 'places' array */
            jPlaces = jObject.getJSONArray(&quot;predictions&quot;);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        /** Invoking getPlaces with the array of json object
        * where each json object represent a place
        */
        return getPlaces(jPlaces);
    }

    private List&lt;HashMap&lt;String, String&gt;&gt; getPlaces(JSONArray jPlaces){
        int placesCount = jPlaces.length();
        List&lt;HashMap&lt;String, String&gt;&gt; placesList = new ArrayList&lt;HashMap&lt;String,String&gt;&gt;();
        HashMap&lt;String, String&gt; place = null;

        /** Taking each place, parses and adds to list object */
        for(int i=0; i&lt;placesCount;i++){
            try {
                /** Call getPlace with place JSON object to parse the place */
                place = getPlace((JSONObject)jPlaces.get(i));
                placesList.add(place);

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

        return placesList;
    }

    /** Parsing the Place JSON object */
    private HashMap&lt;String, String&gt; getPlace(JSONObject jPlace){

        HashMap&lt;String, String&gt; place = new HashMap&lt;String, String&gt;();

        String id=&quot;&quot;;
        String reference=&quot;&quot;;
        String description=&quot;&quot;;

        try {

            description = jPlace.getString(&quot;description&quot;);
            id = jPlace.getString(&quot;id&quot;);
            reference = jPlace.getString(&quot;reference&quot;);

            place.put(&quot;description&quot;, description);
            place.put(&quot;_id&quot;,id);
            place.put(&quot;reference&quot;,reference);

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

</pre><hr
/><p><strong>15. Create the class file src/in/wptrafficanalyzer/locationactionbarcompatsearchviewv2/PlaceDetailsJSONParser.java</strong></p><pre class="brush: java; highlight: [33,34,35]; title: ; notranslate">
package in.wptrafficanalyzer.locationactionbarcompatsearchviewv2;

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

import org.json.JSONException;
import org.json.JSONObject;

public class PlaceDetailsJSONParser {

    /** Receives a JSONObject and returns a list */
    public List&lt;HashMap&lt;String,String&gt;&gt; parse(JSONObject jObject){

        Double lat = Double.valueOf(0);
        Double lng = Double.valueOf(0);
        String formattedAddress = &quot;&quot;;

        HashMap&lt;String, String&gt; hm = new HashMap&lt;String, String&gt;();
        List&lt;HashMap&lt;String, String&gt;&gt; list = new ArrayList&lt;HashMap&lt;String,String&gt;&gt;();

        try {
            lat = (Double)jObject.getJSONObject(&quot;result&quot;).getJSONObject(&quot;geometry&quot;).getJSONObject(&quot;location&quot;).get(&quot;lat&quot;);
            lng = (Double)jObject.getJSONObject(&quot;result&quot;).getJSONObject(&quot;geometry&quot;).getJSONObject(&quot;location&quot;).get(&quot;lng&quot;);
            formattedAddress = (String) jObject.getJSONObject(&quot;result&quot;).get(&quot;formatted_address&quot;);

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

        hm.put(&quot;lat&quot;, Double.toString(lat));
        hm.put(&quot;lng&quot;, Double.toString(lng));
        hm.put(&quot;formatted_address&quot;,formattedAddress);

        list.add(hm);

        return list;
    }
}
</pre><hr
/><p><strong>16. Create the file src/in/wptrafficanalyzer/locationactionbarcompatsearchviewv2/PlaceProvider.java</strong></p><pre class="brush: java; highlight: [30,32,38,39,41,42,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,109,110,140,141,164,165,212,213,257,258,282,283,292,293,304]; title: ; notranslate">
package in.wptrafficanalyzer.locationactionbarcompatsearchviewv2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.util.Log;

public class PlaceProvider extends ContentProvider {

    public static final String AUTHORITY = &quot;in.wptrafficanalyzer.locationsherlocksearchviewmapv2.PlaceProvider&quot;;

    public static final Uri SEARCH_URI = Uri.parse(&quot;content://&quot;+AUTHORITY+&quot;/search&quot;);

    public static final Uri DETAILS_URI = Uri.parse(&quot;content://&quot;+AUTHORITY+&quot;/details&quot;);

    private static final int SEARCH = 1;
    private static final int SUGGESTIONS = 2;
    private static final int DETAILS = 3;

    // Obtain browser key from https://code.google.com/apis/console
    String mKey = &quot;key=YOUR_BROWSER_KEY&quot;;

    // Defines a set of uris allowed with this content provider
    private static final UriMatcher mUriMatcher = buildUriMatcher();

    private static UriMatcher buildUriMatcher() {

        UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

        // URI for &quot;Go&quot; button
        uriMatcher.addURI(AUTHORITY, &quot;search&quot;, SEARCH );

        // URI for suggestions in Search Dialog
        uriMatcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY,SUGGESTIONS);

        // URI for Details
        uriMatcher.addURI(AUTHORITY, &quot;details&quot;,DETAILS);

        return uriMatcher;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
        String[] selectionArgs, String sortOrder) {
        Cursor c = null;

        PlaceJSONParser parser = new PlaceJSONParser();
        PlaceDetailsJSONParser detailsParser = new PlaceDetailsJSONParser();

        String jsonString = &quot;&quot;;
        String jsonPlaceDetails = &quot;&quot;;

        List&lt;HashMap&lt;String, String&gt;&gt; list = null;
        List&lt;HashMap&lt;String, String&gt;&gt; detailsList = null;

        MatrixCursor mCursor = null;

        switch(mUriMatcher.match(uri)){
        case SEARCH:
            // Defining a cursor object with columns description, lat and lng
            mCursor = new MatrixCursor(new String[] { &quot;description&quot;,&quot;lat&quot;,&quot;lng&quot; });

            // Create a parser object to parse places in JSON format
            parser = new PlaceJSONParser();

            // Create a parser object to parse place details in JSON format
            detailsParser = new PlaceDetailsJSONParser();

            // Get Places from Google Places API
            jsonString = getPlaces(selectionArgs);
            try {
                // Parse the places ( JSON =&gt; List )
                list = parser.parse(new JSONObject(jsonString));

                // Finding latitude and longitude for each places using Google Places Details API
                for(int i=0;i&lt;list.size();i++){
                    HashMap&lt;String, String&gt; hMap = (HashMap&lt;String, String&gt;) list.get(i);

                    detailsParser =new PlaceDetailsJSONParser();

                    // Get Place details
                    jsonPlaceDetails = getPlaceDetails(hMap.get(&quot;reference&quot;));

                    // Parse the details ( JSON =&gt; List )
                    detailsList = detailsParser.parse(new JSONObject(jsonPlaceDetails));

                    // Creating cursor object with places
                    for(int j=0;j&lt;detailsList.size();j++){
                        HashMap&lt;String, String&gt; hMapDetails = detailsList.get(j);

                        // Adding place details to cursor
                        mCursor.addRow(new String[]{ hMap.get(&quot;description&quot;) , hMapDetails.get(&quot;lat&quot;) , hMapDetails.get(&quot;lng&quot;) });
                    }

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

        case SUGGESTIONS :

            // Defining a cursor object with columns id, SUGGEST_COLUMN_TEXT_1, SUGGEST_COLUMN_INTENT_EXTRA_DATA
            mCursor = new MatrixCursor(new String[] { &quot;_id&quot;, SearchManager.SUGGEST_COLUMN_TEXT_1, SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA } );

            // Creating a parser object to parse places in JSON format
            parser = new PlaceJSONParser();

            // Get Places from Google Places API
            jsonString = getPlaces(selectionArgs);

            try {
                // Parse the places ( JSON =&gt; List )
                list = parser.parse(new JSONObject(jsonString));

                // Creating cursor object with places
                for(int i=0;i&lt;list.size();i++){
                    HashMap&lt;String, String&gt; hMap = (HashMap&lt;String, String&gt;) list.get(i);

                    // Adding place details to cursor
                    mCursor.addRow(new String[] { Integer.toString(i), hMap.get(&quot;description&quot;), hMap.get(&quot;reference&quot;) });
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            c = mCursor;
            break;

        case DETAILS :
            // Defining a cursor object with columns description, lat and lng
            mCursor = new MatrixCursor(new String[] { &quot;description&quot;,&quot;lat&quot;,&quot;lng&quot; });

            detailsParser = new PlaceDetailsJSONParser();
            jsonPlaceDetails = getPlaceDetails(selectionArgs[0]);
            try {
                detailsList = detailsParser.parse(new JSONObject(jsonPlaceDetails));
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            for(int j=0;j&lt;detailsList.size();j++){
                HashMap&lt;String, String&gt; hMapDetails = detailsList.get(j);
                mCursor.addRow(new String[]{ hMapDetails.get(&quot;formatted_address&quot;) , hMapDetails.get(&quot;lat&quot;) , hMapDetails.get(&quot;lng&quot;) });
            }
            c = mCursor;
            break;
        }
        return c;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public String getType(Uri uri) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean onCreate() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
        String[] selectionArgs) {
        // TODO Auto-generated method stub
        return 0;
    }

    /** A method to download json data from url */
    private String downloadUrl(String strUrl) throws IOException{
        String data = &quot;&quot;;
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try{
            URL url = new URL(strUrl);

            // Creating an http connection to communicate with url
            urlConnection = (HttpURLConnection) url.openConnection();

            // Connecting to url
            urlConnection.connect();

            // Reading data from url
            iStream = urlConnection.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

            StringBuffer sb = new StringBuffer();

            String line = &quot;&quot;;
            while( ( line = br.readLine()) != null){
                sb.append(line);
            }

            data = sb.toString();

            br.close();

        }catch(Exception e){
           Log.d(&quot;Exception while downloading url&quot;, e.toString());
        }finally{
            iStream.close();
            urlConnection.disconnect();
        }
        return data;
    }

    private String getPlaceDetailsUrl(String ref){

        // reference of place
        String reference = &quot;reference=&quot;+ref;

        // Sensor enabled
        String sensor = &quot;sensor=false&quot;;

        // Building the parameters to the web service
        String parameters = reference+&quot;&amp;&quot;+sensor+&quot;&amp;&quot;+mKey;

        // Output format
        String output = &quot;json&quot;;

        // Building the url to the web service
        String url = &quot;https://maps.googleapis.com/maps/api/place/details/&quot;+output+&quot;?&quot;+parameters;

        return url;
    }

    private String getPlacesUrl(String qry){

        try {
            qry = &quot;input=&quot; + URLEncoder.encode(qry, &quot;utf-8&quot;);
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        // Sensor enabled
        String sensor = &quot;sensor=false&quot;;

        // place type to be searched
        String types = &quot;types=geocode&quot;;

        // Building the parameters to the web service
        String parameters = qry+&quot;&amp;&quot;+types+&quot;&amp;&quot;+sensor+&quot;&amp;&quot;+mKey;

        // Output format
        String output = &quot;json&quot;;
        // Building the url to the web service
        String url = &quot;https://maps.googleapis.com/maps/api/place/autocomplete/&quot;+output+&quot;?&quot;+parameters;
        return url;
    }

    private String getPlaces(String[] params){
        // For storing data from web service
        String data = &quot;&quot;;
        String url = getPlacesUrl(params[0]);
        try{
            // Fetching the data from web service in background
            data = downloadUrl(url);
        }catch(Exception e){
            Log.d(&quot;Background Task&quot;,e.toString());
        }
        return data;
    }

    private String getPlaceDetails(String reference){
        String data = &quot;&quot;;
        String url = getPlaceDetailsUrl(reference);
        try {
            data = downloadUrl(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }
}
</pre><p><em>Note : Update &#8220;YOUR_BROWSER_KEY on line 39 with the browser key obtained in Step 10.</em></p><hr
/><p><strong>17. Update the class MainActivity in the file src/in/wptrafficanalyzer/locationactionbarcompatsearchviewv2/MainActivity.java</strong></p><pre class="brush: java; highlight: [24,37,40,41,42,43,44,45,46,48,49,50,51,52,53,55,56,57,58,59,61,62,63,64,65,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123]; title: ; notranslate">

package in.wptrafficanalyzer.locationactionbarcompatsearchviewv2;

import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends ActionBarActivity implements LoaderCallbacks&lt;Cursor&gt;{

    GoogleMap mGoogleMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

        mGoogleMap = fragment.getMap();

        handleIntent(getIntent());
    }

    private void handleIntent(Intent intent){
        if(intent.getAction().equals(Intent.ACTION_SEARCH)){
            doSearch(intent.getStringExtra(SearchManager.QUERY));
        }else if(intent.getAction().equals(Intent.ACTION_VIEW)){
            getPlace(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        handleIntent(intent);
    }

    private void doSearch(String query){
        Bundle data = new Bundle();
        data.putString(&quot;query&quot;, query);
        getSupportLoaderManager().restartLoader(0, data, this);
    }

    private void getPlace(String query){
        Bundle data = new Bundle();
        data.putString(&quot;query&quot;, query);
        getSupportLoaderManager().restartLoader(1, data, this);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);

        // Get the SearchView and set the searchable configuration
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);

        MenuItem searchItem = menu.findItem(R.id.action_search);

        SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);

        // searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

        // Assumes current activity is the searchable activity
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        // searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default

        return super.onCreateOptionsMenu(menu);
    }
    @Override
    public android.support.v4.content.Loader&lt;Cursor&gt; onCreateLoader(int arg0,
        Bundle query) {
        CursorLoader cLoader = null;

        if(arg0==0)
            cLoader = new CursorLoader(getBaseContext(), PlaceProvider.SEARCH_URI, null, null, new String[]{ query.getString(&quot;query&quot;) }, null);
        else if(arg0==1)
            cLoader = new CursorLoader(getBaseContext(), PlaceProvider.DETAILS_URI, null, null, new String[]{ query.getString(&quot;query&quot;) }, null);
        return cLoader;
    }
    @Override
    public void onLoadFinished(android.support.v4.content.Loader&lt;Cursor&gt; arg0,
        Cursor c) {

        showLocations(c);
    }

    @Override
    public void onLoaderReset(android.support.v4.content.Loader&lt;Cursor&gt; arg0) {
        // TODO Auto-generated method stub
    }

    private void showLocations(Cursor c){
        MarkerOptions markerOptions = null;
        LatLng position = null;
        mGoogleMap.clear();
        while(c.moveToNext()){
            markerOptions = new MarkerOptions();
            position = new LatLng(Double.parseDouble(c.getString(1)),Double.parseDouble(c.getString(2)));
            markerOptions.position(position);
            markerOptions.title(c.getString(0));
            mGoogleMap.addMarker(markerOptions);
        }
        if(position!=null){
            CameraUpdate cameraPosition = CameraUpdateFactory.newLatLng(position);
            mGoogleMap.animateCamera(cameraPosition);
        }
    }
}

</pre><hr
/><p><strong>18. Update the configuration file /res/xml/searchable.xml</strong></p><pre class="brush: xml; highlight: [7]; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;searchable xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:label=&quot;@string/app_name&quot;
    android:hint=&quot;@string/search_hint&quot;
    android:searchSettingsDescription=&quot;@string/search_settings&quot;

    android:searchSuggestAuthority=&quot;in.wptrafficanalyzer.locationactionbarcompatsearchviewv2.PlaceProvider&quot;
    android:searchSuggestIntentAction=&quot;android.intent.action.VIEW&quot;
    android:searchSuggestSelection=&quot; ?&quot;
    android:searchSuggestThreshold=&quot;2&quot; &gt;

&lt;/searchable&gt;
</pre><hr
/><p><strong>19. Update the file AndroidManifest.xml</strong></p><pre class="brush: xml; highlight: [44,54,55,56,58,59,60,62,63,64,68,69,70,71,74,75,76]; title: ; 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;in.wptrafficanalyzer.locationactionbarcompatsearchviewv2&quot;
    android:versionCode=&quot;1&quot;
    android:versionName=&quot;1.0&quot; &gt;

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

    &lt;!-- Protect the map component of the application using application signature --&gt;
    &lt;permission
        android:name=&quot;in.wptrafficanalyzer.locationactionbarcompatsearchviewv2.permission.MAPS_RECEIVE&quot;
        android:protectionLevel=&quot;signature&quot; /&gt;

    &lt;!-- Allows to receive map --&gt;
    &lt;uses-permission android:name=&quot;in.wptrafficanalyzer.locationactionbarcompatsearchviewv2.permission.MAPS_RECEIVE&quot; /&gt;

    &lt;!-- Used by the Google Maps Android API V2 to download map tiles from Google Maps servers --&gt;
    &lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;

    &lt;!-- Allows the Google Maps Android API V2 to cache map tile data in the device's external storage area --&gt;
    &lt;uses-permission android:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot; /&gt;

    &lt;!-- Allows the Google Maps Android API V2 to use WiFi or mobile cell data (or both) to determine the device's location --&gt;
    &lt;uses-permission android:name=&quot;android.permission.ACCESS_COARSE_LOCATION&quot; /&gt;

    &lt;!-- Allows the Google Maps Android API V2 to use the Global Positioning System (GPS)
    to determine the device's location to within a very small area --&gt;
    &lt;uses-permission android:name=&quot;android.permission.ACCESS_FINE_LOCATION&quot; /&gt;

    &lt;!-- Allows to contact Google Serves --&gt;
    &lt;uses-permission android:name=&quot;com.google.android.providers.gsf.permission.READ_GSERVICES&quot; /&gt;

    &lt;!-- Google Maps Android API V2 requires OpenGL ES version 2 --&gt;
    &lt;uses-feature
        android:glEsVersion=&quot;0x00020000&quot;
        android:required=&quot;true&quot; /&gt;

    &lt;application
        android:allowBackup=&quot;true&quot;
        android:icon=&quot;@drawable/ic_launcher&quot;
        android:label=&quot;@string/app_name&quot;
        android:theme=&quot;@style/Theme.AppCompat&quot; &gt;
        &lt;activity
            android:name=&quot;in.wptrafficanalyzer.locationactionbarcompatsearchviewv2.MainActivity&quot;
            android:label=&quot;@string/app_name&quot;
            android:launchMode=&quot;singleTop&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;intent-filter&gt;
                &lt;action android:name=&quot;android.intent.action.SEARCH&quot; /&gt;
            &lt;/intent-filter&gt;

            &lt;!-- Points to searchable activity --&gt;
            &lt;meta-data android:name=&quot;android.app.default_searchable&quot;
                android:value=&quot;.MainActivity&quot; /&gt;

            &lt;!-- Points to searchable meta data --&gt;
            &lt;meta-data android:name=&quot;android.app.searchable&quot;
                android:resource=&quot;@xml/searchable&quot;/&gt;

        &lt;/activity&gt;

        &lt;provider
            android:name=&quot;.PlaceProvider&quot;
            android:authorities=&quot;in.wptrafficanalyzer.locationactionbarcompatsearchviewv2.PlaceProvider&quot;
            android:exported=&quot;false&quot; /&gt;

        &lt;!-- Specifies the Android API Key, which is obtained from Google API Console --&gt;
        &lt;meta-data
            android:name=&quot;com.google.android.maps.v2.API_KEY&quot;
            android:value=&quot;YOUR_ANDROID_API_KEY&quot; /&gt;

    &lt;/application&gt;
&lt;/manifest&gt;
</pre><p><em>Note : Update &#8220;YOUR_ANDROID_API_KEY on line 76 with the Android API key obtained in Step 9.</em></p><hr
/><p><strong>20. Screenshots of the application</strong></p><div
id="attachment_8712" class="wp-caption aligncenter" style="width: 250px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/08/location_actionbarcompat_searchview_v2_screenshot.png"><img
class="size-full wp-image-8712" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/08/location_actionbarcompat_searchview_v2_screenshot.png" alt="Searching places in SearchView Widget" width="240" height="320" /></a><p
class="wp-caption-text">Figure 7 : Searching places in SearchView Widget</p></div><pre></pre><div
id="attachment_8713" class="wp-caption aligncenter" style="width: 250px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/08/location_actionbarcompat_searchview_v2_show.png"><img
class="size-full wp-image-8713" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/08/location_actionbarcompat_searchview_v2_show.png" alt="Showing selected place in Google Maps" width="240" height="320" /></a><p
class="wp-caption-text">Figure 8 : Showing selected place in Google Maps</p></div><hr
/><p><strong>21. Download Source code</strong></p><p
style="text-align: center"></p><div
class='w3eden'><div
class="wpdm-link-tpl link-btn light" data-durl="http://wptrafficanalyzer.in/blog/?wpdmdl=9373" ><div
class="media"><div
class="pull-left"><img
class="wpdm_icon" src="http://wptrafficanalyzer.in/blog/wp-content/plugins/download-manager/file-type-icons/zip.png" onError='this.src="http://wptrafficanalyzer.in/blog/wp-content/plugins/download-manager/file-type-icons/_blank.png";' /></div><div
class="media-body"><strong
class="ptitle">Android SearchView Widget with ActionBarCompat library <span
class="label label-default" style="font-weight: 400;">601.99 KB</span></strong><div><strong><a
class='wpdm-download-link wpdm-download-locked [btnclass]' rel='noindex nofollow' href='http://wptrafficanalyzer.in/blog/?wpdmdl=9373'><i
class=''></i>Download Source Code</a></strong></div></div></div></div><div
style="clear: both"></div></div><hr
/><div><b>How to hire me?</b><br
/><img
style='float:left;padding:10px' src='http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/george_wpta.jpg'><p>I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in<br
/><br
/>You can hire me on hourly basis or on project basis for Android applications development.<br
/><br
/>For hiring me, please mail your requirements to info@wptrafficanalyzer.in.<br
/></p><p><i><u>My other blogs</u></i><br
/><a
href='http://store4js.blogspot.com/' rel='nofollow' target='_blank'>store4js.blogspot.com</a></p><hr
/><p
style='clear:both'></p></div>]]></content:encoded> <wfw:commentRss>http://wptrafficanalyzer.in/blog/android-searchview-widget-with-actionbarcompat-library/feed/</wfw:commentRss> <slash:comments>11</slash:comments> </item> <item><title>Android using custom ttf fonts in WebView</title><link>http://wptrafficanalyzer.in/blog/android-using-custom-ttf-fonts-in-webview/</link> <comments>http://wptrafficanalyzer.in/blog/android-using-custom-ttf-fonts-in-webview/#comments</comments> <pubDate>Tue, 30 Jul 2013 00:54:46 +0000</pubDate> <dc:creator>George Mathew</dc:creator> <category><![CDATA[Android]]></category> <category><![CDATA[custom font]]></category> <category><![CDATA[ttf]]></category> <category><![CDATA[WebView]]></category><guid
isPermaLink="false">http://wptrafficanalyzer.in/blog/?p=8644</guid> <description><![CDATA[In this article, we will see how to use custom fonts in WebView of Android application.The same strategy can be used to display local language contents in WebView. This application renders the text in a WebView using Chancery font. This application is developed in Eclipse 4.2.0 with ADT plugin 22.0.4. 1. Create an Android application with the given below details Application Name : WebViewCustomFont Project Name : WebViewCustomFont Package Name : in.wptrafficanalyzer.webviewcustomfont Minimum Required SDK : API 8 : Android 2.2 ( Froyo ) Target SDK : API 17 : Android 4.2 ( Jelly Bean ) 2. Create a directory &#8220;fonts&#8221; under &#8220;assets&#8221; directory 3. Download &#8220;Chancery&#8221; font and copy to the assets/fonts directory We can download a &#8220;Chancery&#8221; font from here 4. Update the layout file res/layout/activity_main.xml 5. Create an html file assets/demo.html 6. Update the MainActivity class in the file src/in/wptrafficanalyzer/webviewcustomfont/MainActivity.java 7. Running the application 8. Download Source Code How to hire me?I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.inYou can hire me on hourly basis or on project basis for Android applications development.For hiring me, please mail your requirements to info@wptrafficanalyzer.in.My other blogsstore4js.blogspot.com]]></description> <content:encoded><![CDATA[<p>In this article, we will see how to use custom fonts in WebView of Android application.The same strategy can be used to display local language contents in WebView.</p><p
style="text-align: center"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <ins
class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-0084597063187020"
data-ad-slot="4112080501"></ins><script>(adsbygoogle=window.adsbygoogle||[]).push({});</script></p><p>This application renders the text in a WebView using Chancery font.</p><p>This application is developed in Eclipse 4.2.0 with ADT plugin 22.0.4.</p><hr
/><p><strong>1. Create an Android application with the given below details</strong></p><p>Application Name : WebViewCustomFont</p><p>Project Name : WebViewCustomFont</p><p>Package Name : in.wptrafficanalyzer.webviewcustomfont</p><p>Minimum Required SDK : API 8 : Android 2.2 ( Froyo )</p><p>Target SDK : API 17 : Android 4.2 ( Jelly Bean )</p><div><hr
/></div><p><strong>2. Create a directory &#8220;fonts&#8221; under &#8220;assets&#8221; directory</strong></p><hr
/><p><strong>3. Download &#8220;Chancery&#8221; font and copy to the assets/fonts directory</strong></p><p>We can download a &#8220;Chancery&#8221; font from <a
title="Chancery Font" href="http://www.dafont.com/black-chancery.font" rel="nofollow" target="_blank">here</a></p><hr
/><p><strong>4. Update the layout file res/layout/activity_main.xml</strong></p><pre class="brush: xml; highlight: [7,8,9,10,11]; title: ; notranslate">

&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    tools:context=&quot;.MainActivity&quot; &gt;

    &lt;WebView
        android:id=&quot;@+id/webview&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;match_parent&quot;
        android:text=&quot;@string/hello_world&quot; /&gt;

&lt;/RelativeLayout&gt;

</pre><hr
/><p><strong>5. Create an html file assets/demo.html</strong></p><pre class="brush: xml; highlight: [7,8,9,10,11]; title: ; notranslate">

&lt;html&gt;
    &lt;head&gt;
        &lt;meta http-equiv=&quot;content-type&quot; content=&quot;text/html;&quot; charset=&quot;UTF-8&quot;&gt;
            &lt;style&gt;
                /** Specify a font named &quot;MyFont&quot;,
                and specify the URL where it can be found: */
                @font-face {
                    font-family: &quot;MyFont&quot;;
                    src: url('file:///android_asset/fonts/BLKCHCRY.TTF');
                }
                h3 { font-family:&quot;MyFont&quot;}
            &lt;/style&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;h3&gt;
            Welcome to CustomFont Demo
        &lt;/h3&gt;
    &lt;/body&gt;
&lt;/html&gt;

</pre><hr
/><p><strong>6. Update the MainActivity class in the file src/in/wptrafficanalyzer/webviewcustomfont/MainActivity.java</strong></p><pre class="brush: java; highlight: [17,18,19,20,21]; title: ; notranslate">

package in.wptrafficanalyzer.webviewcustomfont;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.webkit.WebView;

public class MainActivity extends Activity {

    WebView mWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Getting reference to WebView of the activity_main layout
        mWebView = (WebView) findViewById(R.id.webview);

        // Loading an html page into webview
        mWebView.loadUrl(&quot;file:///android_asset/demo.html&quot;);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

</pre><hr
/><p
style="text-align: center"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <ins
class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-0084597063187020"
data-ad-slot="3824266707"></ins><script>(adsbygoogle=window.adsbygoogle||[]).push({});</script></p><hr
/><p><strong>7. Running the application</strong></p><div
id="attachment_8663" class="wp-caption aligncenter" style="width: 444px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/webview_custom_font_screenshot.png"><img
class="size-full wp-image-8663" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/webview_custom_font_screenshot.png" alt="WebView CustomFont Demo in Action" width="434" height="415" /></a><p
class="wp-caption-text">Figure 1 : WebView CustomFont Demo in Action</p></div><hr
/><p><strong>8. Download Source Code</strong></p><p
style="text-align: center"></p><div
class='w3eden'><div
class="wpdm-link-tpl link-btn light" data-durl="http://wptrafficanalyzer.in/blog/?wpdmdl=9372" ><div
class="media"><div
class="pull-left"><img
class="wpdm_icon" src="http://wptrafficanalyzer.in/blog/wp-content/plugins/download-manager/file-type-icons/zip.png" onError='this.src="http://wptrafficanalyzer.in/blog/wp-content/plugins/download-manager/file-type-icons/_blank.png";' /></div><div
class="media-body"><strong
class="ptitle">Android using custom ttf font in WebView <span
class="label label-default" style="font-weight: 400;">540.18 KB</span></strong><div><strong><a
class='wpdm-download-link wpdm-download-locked [btnclass]' rel='noindex nofollow' href='http://wptrafficanalyzer.in/blog/?wpdmdl=9372'><i
class=''></i>Download Full Source Code</a></strong></div></div></div></div><div
style="clear: both"></div></div><hr
/><div><b>How to hire me?</b><br
/><img
style='float:left;padding:10px' src='http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/george_wpta.jpg'><p>I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in<br
/><br
/>You can hire me on hourly basis or on project basis for Android applications development.<br
/><br
/>For hiring me, please mail your requirements to info@wptrafficanalyzer.in.<br
/></p><p><i><u>My other blogs</u></i><br
/><a
href='http://store4js.blogspot.com/' rel='nofollow' target='_blank'>store4js.blogspot.com</a></p><hr
/><p
style='clear:both'></p></div>]]></content:encoded> <wfw:commentRss>http://wptrafficanalyzer.in/blog/android-using-custom-ttf-fonts-in-webview/feed/</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>Action bar menus and SplitActionBar using ActionBarCompat library in Android</title><link>http://wptrafficanalyzer.in/blog/action-bar-menus-and-splitactionbar-using-actionbarcompat-library-in-android/</link> <comments>http://wptrafficanalyzer.in/blog/action-bar-menus-and-splitactionbar-using-actionbarcompat-library-in-android/#comments</comments> <pubDate>Thu, 25 Jul 2013 14:22:41 +0000</pubDate> <dc:creator>George Mathew</dc:creator> <category><![CDATA[Android]]></category> <category><![CDATA[action bar]]></category> <category><![CDATA[action item]]></category> <category><![CDATA[actionbarcompat]]></category> <category><![CDATA[menu]]></category> <category><![CDATA[split action bar]]></category><guid
isPermaLink="false">http://wptrafficanalyzer.in/blog/?p=8576</guid> <description><![CDATA[In the article titled &#8220;Adding Action items and Overflow menu items to Action Bar in Android&#8220;, we have seen how to add action items and split action bar items to action bar in Android. Since action bar is introduced in Android 3.0 ( API Level 11 ) , we can not run that application in Android versions prior to Honeycomb. In order to overcome this limitation, we can make use ActionBarCompat library available with Android support library revision 18. Using ActionBarCompat library we can implement action bars back upto Android API Level 7. In this article, we will develop an Android application that contain action items and split action bar. This application is developed in Eclipse 4.2.0 with ADT plugin 22.0.4. 1. Create new Android application Application Name : ActionBarCompatMenu Project Name : ActionBarCompatMenu Package Name : in.wptrafficanalyzer.actionbarcompatmenu Minimum Required SDK : API 8 : Android 2.2 ( Froyo ) Target SDK : API 17 : Android 4.2 ( Jelly Bean ) 2. Setup ActionBarCompat library in Eclipse Please refer the article titled &#8220;Android &#8211; Setting up ActionBarCompat support library in Eclipse&#8221; 3. Add reference to ActionBarCompat support library 4. Add menu icons to this project From the given below links, download [&#8230;]]]></description> <content:encoded><![CDATA[<p>In the article titled &#8220;<a
title="Adding Action items and Overflow menu items to Action Bar in Android" href="http://wptrafficanalyzer.in/blog/adding-action-items-and-overflow-menu-items-to-action-bar-in-android" target="_blank">Adding Action items and Overflow menu items to Action Bar in Android</a>&#8220;, we have seen how to add action items and split action bar items to action bar in Android.</p><p
style="text-align: center"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <ins
class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-0084597063187020"
data-ad-slot="4112080501"></ins><script>(adsbygoogle=window.adsbygoogle||[]).push({});</script></p><p>Since action bar is introduced in Android 3.0 ( API Level 11 ) , we can not run that application in Android versions prior to Honeycomb.</p><p>In order to overcome this limitation, we can make use ActionBarCompat library available with Android support library revision 18. Using ActionBarCompat library we can implement action bars back upto Android API Level 7.</p><p>In this article, we will develop an Android application that contain action items and split action bar.</p><p>This application is developed in Eclipse 4.2.0 with ADT plugin 22.0.4.</p><p
style="text-align: center"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <ins
class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-0084597063187020"
data-ad-slot="3824266707"></ins><script>(adsbygoogle=window.adsbygoogle||[]).push({});</script></p><hr
/><p><strong>1. Create new Android application</strong></p><p>Application Name : ActionBarCompatMenu</p><p>Project Name : ActionBarCompatMenu</p><p>Package Name : in.wptrafficanalyzer.actionbarcompatmenu</p><p>Minimum Required SDK : API 8 : Android 2.2 ( Froyo )</p><p>Target SDK : API 17 : Android 4.2 ( Jelly Bean )</p><hr
/><p><strong>2. Setup ActionBarCompat library in Eclipse</strong></p><p>Please refer the article titled &#8220;<a
title="Android - Setting up ActionBarCompat support library in Eclipse" href="http://wptrafficanalyzer.in/blog/android-setting-up-actionbarcompat-support-library-in-eclipse" rel="nofollow" target="_blank">Android &#8211; Setting up ActionBarCompat support library in Eclipse</a>&#8221;</p><hr
/><p><strong>3. Add reference to ActionBarCompat support library</strong></p><div
id="attachment_8580" class="wp-caption aligncenter" style="width: 460px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/action_bar_compat_menu_reference_library.png"><img
class="size-full wp-image-8580" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/action_bar_compat_menu_reference_library.png" alt="Link ActionBarCompat library to this project" width="450" height="549" /></a><p
class="wp-caption-text">Figure 1 : Link ActionBarCompat library to this project</p></div><hr
/><p><strong>4. Add menu icons to this project</strong></p><p>From the given below links, download the files drawable-mdpi.zip, drawable-hdpi.zip and drawable-xhdpi.zip and extract to the folders drawable-mdpi, drawable-hdpi and drawable-xhdpi respectively</p><div
class='w3eden'><div
class="wpdm-link-tpl link-btn light" data-durl="http://wptrafficanalyzer.in/blog/?wpdmdl=9194" ><div
class="media"><div
class="pull-left"><img
class="wpdm_icon" src="http://wptrafficanalyzer.in/blog/wp-content/plugins/download-manager/file-type-icons/zip.png" onError='this.src="http://wptrafficanalyzer.in/blog/wp-content/plugins/download-manager/file-type-icons/_blank.png";' /></div><div
class="media-body"><strong
class="ptitle">Adding Menus to Action Bar <span
class="label label-default" style="font-weight: 400;">6.49 KB</span></strong><div><strong><a
class='wpdm-download-link wpdm-download-locked [btnclass]' rel='noindex nofollow' href='http://wptrafficanalyzer.in/blog/?wpdmdl=9194'><i
class=''></i>Download drawable-mdpi.zip</a></strong></div></div></div></div><div
style="clear: both"></div></div><div
class='w3eden'><div
class="wpdm-link-tpl link-btn light" data-durl="http://wptrafficanalyzer.in/blog/?wpdmdl=9195" ><div
class="media"><div
class="pull-left"><img
class="wpdm_icon" src="http://wptrafficanalyzer.in/blog/wp-content/plugins/download-manager/file-type-icons/zip.png" onError='this.src="http://wptrafficanalyzer.in/blog/wp-content/plugins/download-manager/file-type-icons/_blank.png";' /></div><div
class="media-body"><strong
class="ptitle">Adding Menus to Action Bar - drawable_hdpi.zip <span
class="label label-default" style="font-weight: 400;">7.44 KB</span></strong><div><strong><a
class='wpdm-download-link wpdm-download-locked [btnclass]' rel='noindex nofollow' href='http://wptrafficanalyzer.in/blog/?wpdmdl=9195'><i
class=''></i>Download drawable-hdpi.zip</a></strong></div></div></div></div><div
style="clear: both"></div></div><div
class='w3eden'><div
class="wpdm-link-tpl link-btn light" data-durl="http://wptrafficanalyzer.in/blog/?wpdmdl=9196" ><div
class="media"><div
class="pull-left"><img
class="wpdm_icon" src="http://wptrafficanalyzer.in/blog/wp-content/plugins/download-manager/file-type-icons/zip.png" onError='this.src="http://wptrafficanalyzer.in/blog/wp-content/plugins/download-manager/file-type-icons/_blank.png";' /></div><div
class="media-body"><strong
class="ptitle">Adding Menus to Action Bar - drawable_xhdpi.zip <span
class="label label-default" style="font-weight: 400;">8.39 KB</span></strong><div><strong><a
class='wpdm-download-link wpdm-download-locked [btnclass]' rel='noindex nofollow' href='http://wptrafficanalyzer.in/blog/?wpdmdl=9196'><i
class=''></i>Download drawable-xhdpi.zip</a></strong></div></div></div></div><div
style="clear: both"></div></div><div><hr
/></div><div><strong>5. Update the file res/values/strings.xml</strong></div><div><pre class="brush: xml; highlight: [7,8,9,10,11,12]; title: ; 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;ActionBarCompatMenu&lt;/string&gt;
    &lt;string name=&quot;action_settings&quot;&gt;Settings&lt;/string&gt;
    &lt;string name=&quot;hello_world&quot;&gt;Hello world!&lt;/string&gt;

    &lt;string name=&quot;phone&quot;&gt;Phone&lt;/string&gt;
    &lt;string name=&quot;computer&quot;&gt;Computer&lt;/string&gt;
    &lt;string name=&quot;gamepad&quot;&gt;Gamepad&lt;/string&gt;
    &lt;string name=&quot;camera&quot;&gt;Camera&lt;/string&gt;
    &lt;string name=&quot;video&quot;&gt;Video&lt;/string&gt;
    &lt;string name=&quot;email&quot;&gt;EMail&lt;/string&gt;
&lt;/resources&gt;
</pre><hr
/><p><strong>6. Update the menu file res/menu/main.xml</strong></p><p><em>Note : Please see the namespace prefix &#8220;myapp&#8221; in the given below code</em></p><pre class="brush: xml; highlight: [2,8,14,20,26,32,38]; title: ; notranslate">
&lt;menu xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:myapp=&quot;http://schemas.android.com/apk/res-auto&quot; &gt;

    &lt;item
        android:id=&quot;@+id/phone&quot;
        android:title=&quot;@string/phone&quot;
        android:icon=&quot;@drawable/phone&quot;
        myapp:showAsAction=&quot;ifRoom|withText&quot; /&gt;

    &lt;item
        android:id=&quot;@+id/computer&quot;
        android:title=&quot;@string/computer&quot;
        android:icon=&quot;@drawable/computer&quot;
        myapp:showAsAction=&quot;ifRoom|withText&quot; /&gt;

    &lt;item
        android:id=&quot;@+id/gamepad&quot;
        android:title=&quot;@string/gamepad&quot;
        android:icon=&quot;@drawable/gamepad&quot;
        myapp:showAsAction=&quot;ifRoom|withText&quot; /&gt;

    &lt;item
        android:id=&quot;@+id/camera&quot;
        android:title=&quot;@string/camera&quot;
        android:icon=&quot;@drawable/camera&quot;
        myapp:showAsAction=&quot;ifRoom|withText&quot; /&gt;

    &lt;item
        android:id=&quot;@+id/video&quot;
        android:title=&quot;@string/video&quot;
        android:icon=&quot;@drawable/video&quot;
        myapp:showAsAction=&quot;ifRoom|withText&quot; /&gt;

    &lt;item
        android:id=&quot;@+id/email&quot;
        android:title=&quot;@string/email&quot;
        android:icon=&quot;@drawable/email&quot;
        myapp:showAsAction=&quot;ifRoom|withText&quot; /&gt;

&lt;/menu&gt;
</pre><hr
/><p><strong>7. Update the file res/layout/activity_main.xml</strong></p><pre class="brush: xml; highlight: [14]; title: ; notranslate">

&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    android:paddingBottom=&quot;@dimen/activity_vertical_margin&quot;
    android:paddingLeft=&quot;@dimen/activity_horizontal_margin&quot;
    android:paddingRight=&quot;@dimen/activity_horizontal_margin&quot;
    android:paddingTop=&quot;@dimen/activity_vertical_margin&quot;
    tools:context=&quot;.MainActivity&quot; &gt;

    &lt;TextView
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_centerInParent=&quot;true&quot;
        android:text=&quot;@string/hello_world&quot; /&gt;

&lt;/RelativeLayout&gt;

</pre><hr
/><p><strong>8. Update the class MainActivity in the file src/in/wptrafficanalyzer/actionbarcompatmenu/MainActivity.java</strong></p><pre class="brush: java; highlight: [9,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55]; title: ; notranslate">
package in.wptrafficanalyzer.actionbarcompatmenu;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        super.onOptionsItemSelected(item);

        switch(item.getItemId()){
            case R.id.phone:
                Toast.makeText(getBaseContext(), &quot;You selected Phone&quot;, Toast.LENGTH_SHORT).show();
                break;

            case R.id.computer:
                Toast.makeText(getBaseContext(), &quot;You selected Computer&quot;, Toast.LENGTH_SHORT).show();
                break;

            case R.id.gamepad:
                Toast.makeText(getBaseContext(), &quot;You selected Gamepad&quot;, Toast.LENGTH_SHORT).show();
                break;

            case R.id.camera:
                Toast.makeText(getBaseContext(), &quot;You selected Camera&quot;, Toast.LENGTH_SHORT).show();
                break;

            case R.id.video:
                Toast.makeText(getBaseContext(), &quot;You selected Video&quot;, Toast.LENGTH_SHORT).show();
                break;

            case R.id.email:
                Toast.makeText(getBaseContext(), &quot;You selected EMail&quot;, Toast.LENGTH_SHORT).show();
                break;
            }
        return true;
    }
}
</pre><hr
/><p><strong>9. Update the file AndroidManifest.xml</strong></p><pre class="brush: xml; highlight: [15]; title: ; 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;in.wptrafficanalyzer.actionbarcompatmenu&quot;
    android:versionCode=&quot;1&quot;
    android:versionName=&quot;1.0&quot; &gt;

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

    &lt;application
        android:allowBackup=&quot;true&quot;
        android:icon=&quot;@drawable/ic_launcher&quot;
        android:label=&quot;@string/app_name&quot;
        android:theme=&quot;@style/Theme.AppCompat&quot; &gt;
        &lt;activity
            android:name=&quot;in.wptrafficanalyzer.actionbarcompatmenu.MainActivity&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;/application&gt;
&lt;/manifest&gt;

</pre><hr
/><p><strong>10. Screenshot of the application in execution</strong></p><div
id="attachment_8592" class="wp-caption aligncenter" style="width: 250px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/action_bar_compat_menu_screenshot.png"><img
class="size-full wp-image-8592" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/action_bar_compat_menu_screenshot.png" alt="Showing Menus in ActionBar using ActionBarCompat library" width="240" height="320" /></a><p
class="wp-caption-text">Figure 2 : Showing Menus in ActionBar using ActionBarCompat library</p></div><hr
/><p><strong>11. Showing split action bar in Pre Android API Level 11 versions</strong></p><p>If there is not enough room for action menus to align in action bar, then we can move the action menus to the bottom of the screen.</p><p>This is achieved by specifing uiOptions attribute for the activity in AndroidManifest.xml.</p><p>Please see the highlighted text, that splits the actionbar in the given below code.</p><p>The attribute &#8220;uiOptions&#8221; specified in the line 19 is understood only by API Level 14 or higher.</p><p>The meta-data element specified in the lines 24 and 25 is used for older versions.</p><pre class="brush: xml; highlight: [19,24,25]; title: ; 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;in.wptrafficanalyzer.actionbarcompatmenu&quot;
    android:versionCode=&quot;1&quot;
    android:versionName=&quot;1.0&quot; &gt;

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

    &lt;application
        android:allowBackup=&quot;true&quot;
        android:icon=&quot;@drawable/ic_launcher&quot;
        android:label=&quot;@string/app_name&quot;
        android:theme=&quot;@style/Theme.AppCompat&quot; &gt;
        &lt;activity
            android:name=&quot;in.wptrafficanalyzer.actionbarcompatmenu.MainActivity&quot;
            android:label=&quot;@string/app_name&quot;
            android:uiOptions=&quot;splitActionBarWhenNarrow&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;meta-data android:name=&quot;android.support.UI_OPTIONS&quot;
                android:value=&quot;splitActionBarWhenNarrow&quot; /&gt;
            &lt;/activity&gt;
        &lt;/application&gt;
&lt;/manifest&gt;
</pre><hr
/><p><strong>12. Screenshot of the application with Split Action Bar</strong></p><div
id="attachment_8595" class="wp-caption aligncenter" style="width: 250px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/action_bar_compat_menu_split_action_bar.png"><img
class="size-full wp-image-8595" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/action_bar_compat_menu_split_action_bar.png" alt="Showing Split Action Bar using ActionBarCompat support library" width="240" height="320" /></a><p
class="wp-caption-text">Figure 3 : Showing Split Action Bar using ActionBarCompat support library</p></div><hr
/><p><strong>13. Download Full Source Code</strong></p><p
style="text-align: center"></p><div
class='w3eden'><div
class="wpdm-link-tpl link-btn light" data-durl="http://wptrafficanalyzer.in/blog/?wpdmdl=9371" ><div
class="media"><div
class="pull-left"><img
class="wpdm_icon" src="http://wptrafficanalyzer.in/blog/wp-content/plugins/download-manager/file-type-icons/zip.png" onError='this.src="http://wptrafficanalyzer.in/blog/wp-content/plugins/download-manager/file-type-icons/_blank.png";' /></div><div
class="media-body"><strong
class="ptitle">Action bar menus and SplitActionBar using ActionBarCompat library in Android <span
class="label label-default" style="font-weight: 400;">589.85 KB</span></strong><div><strong><a
class='wpdm-download-link wpdm-download-locked [btnclass]' rel='noindex nofollow' href='http://wptrafficanalyzer.in/blog/?wpdmdl=9371'><i
class=''></i>Download Full Source Code</a></strong></div></div></div></div><div
style="clear: both"></div></div><hr
/></div><div><b>How to hire me?</b><br
/><img
style='float:left;padding:10px' src='http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/george_wpta.jpg'><p>I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in<br
/><br
/>You can hire me on hourly basis or on project basis for Android applications development.<br
/><br
/>For hiring me, please mail your requirements to info@wptrafficanalyzer.in.<br
/></p><p><i><u>My other blogs</u></i><br
/><a
href='http://store4js.blogspot.com/' rel='nofollow' target='_blank'>store4js.blogspot.com</a></p><hr
/><p
style='clear:both'></p></div>]]></content:encoded> <wfw:commentRss>http://wptrafficanalyzer.in/blog/action-bar-menus-and-splitactionbar-using-actionbarcompat-library-in-android/feed/</wfw:commentRss> <slash:comments>5</slash:comments> </item> <item><title>Implementing Action Bar using ActionBarCompat support library in Android</title><link>http://wptrafficanalyzer.in/blog/implementing-action-bar-using-actionbarcompat-support-library-in-android/</link> <comments>http://wptrafficanalyzer.in/blog/implementing-action-bar-using-actionbarcompat-support-library-in-android/#comments</comments> <pubDate>Thu, 25 Jul 2013 07:22:29 +0000</pubDate> <dc:creator>George Mathew</dc:creator> <category><![CDATA[Android]]></category> <category><![CDATA[action bar]]></category> <category><![CDATA[actionbarcompat]]></category><guid
isPermaLink="false">http://wptrafficanalyzer.in/blog/?p=8549</guid> <description><![CDATA[We know that, action bar is implemented in Android 3.0 ( Honeycomb or API Level 11) on wards. But we can implement action bar in pre Honycomb versions upto API Level 7 using ActionBarCompat library available with Android support library revision 18. In this article, we will see how to implement action bar in pre honeycomb versions using ActionBarCompat support library. This application is developed in Eclipse 4.2.0 with ADT plugin 22.0.4 1. Create new Android application project Application Name : ActionBarCompatDemo Project Name : ActionBarCompatDemo Package Name : in.wptrafficanalyzer.actionbarcompatdemo Minimum Required SDK : API 8 : Android 2.2 ( Froyo ) Target SDK : API 17 : Android 4.2 ( Jelly Bean ) 2. Setup ActionBarCompat library in Eclipse Please refer the article titled &#8220;Android &#8211; Setting up ActionBarCompat support library in Eclipse&#8221; 3. Add reference to ActionBarCompat library 4. Update the file AndroidManifest.xml Note : As shown in the highlighted line 15,  the activity that implements the action bar should apply the style Theme.AppCompat or Theme.AppCompat.Light or Theme.AppCompat.DarkActionBar 5. Update the class MainActivity in the file src/in/wptrafficanalyzer/actionbarcompatdemo/MainActivity.java Note : As shown in the highlighted line7, the activity should extend the class ActionBarActivity. 6. Screenshot of the application 7. Download Source code How [&#8230;]]]></description> <content:encoded><![CDATA[<p>We know that, action bar is implemented in Android 3.0 ( Honeycomb or API Level 11) on wards.</p><p
style="text-align: center"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <ins
class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-0084597063187020"
data-ad-slot="4112080501"></ins><script>(adsbygoogle=window.adsbygoogle||[]).push({});</script></p><p>But we can implement action bar in pre Honycomb versions upto API Level 7 using ActionBarCompat library available with Android support library revision 18.</p><p>In this article, we will see how to implement action bar in pre honeycomb versions using ActionBarCompat support library.</p><p>This application is developed in Eclipse 4.2.0 with ADT plugin 22.0.4</p><p
style="text-align: center"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <ins
class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-0084597063187020"
data-ad-slot="3824266707"></ins><script>(adsbygoogle=window.adsbygoogle||[]).push({});</script></p><hr
/><p><strong>1. Create new Android application project</strong></p><p>Application Name : ActionBarCompatDemo</p><p>Project Name : ActionBarCompatDemo</p><p>Package Name : in.wptrafficanalyzer.actionbarcompatdemo</p><p>Minimum Required SDK : API 8 : Android 2.2 ( Froyo )</p><p>Target SDK : API 17 : Android 4.2 ( Jelly Bean )</p><hr
/><p><strong>2. Setup ActionBarCompat library in Eclipse</strong></p><p>Please refer the article titled &#8220;<a
title="Android - Setting up ActionBarCompat support library in Eclipse" href="http://wptrafficanalyzer.in/blog/android-setting-up-actionbarcompat-support-library-in-eclipse" rel="nofollow" target="_blank">Android &#8211; Setting up ActionBarCompat support library in Eclipse</a>&#8221;</p><hr
/><p><strong>3. Add reference to ActionBarCompat library</strong></p><div
id="attachment_8550" class="wp-caption aligncenter" style="width: 460px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/action_bar_compat_demo_link.png"><img
class="size-full wp-image-8550" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/action_bar_compat_demo_link.png" alt="Add reference to ActionBarCompat support library" width="450" height="386" /></a><p
class="wp-caption-text">Figure 1 : Add reference to ActionBarCompat support library</p></div><hr
/><p><strong>4. Update the file AndroidManifest.xml</strong></p><p><em>Note : As shown in the highlighted line 15,  the activity that implements the action bar should apply the style <strong>Theme.AppCompat</strong> or <strong>Theme.AppCompat.Light</strong> or <strong>Theme.AppCompat.DarkActionBar</strong></em></p><pre class="brush: xml; highlight: [15]; title: ; 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;in.wptrafficanalyzer.actionbarcompatdemo&quot;
    android:versionCode=&quot;1&quot;
    android:versionName=&quot;1.0&quot; &gt;

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

    &lt;application
        android:allowBackup=&quot;true&quot;
        android:icon=&quot;@drawable/ic_launcher&quot;
        android:label=&quot;@string/app_name&quot;
        android:theme=&quot;@style/Theme.AppCompat&quot; &gt;
        &lt;activity
            android:name=&quot;in.wptrafficanalyzer.actionbarcompatdemo.MainActivity&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;/application&gt;
&lt;/manifest&gt;

</pre><hr
/><p><strong>5. Update the class MainActivity in the file src/in/wptrafficanalyzer/actionbarcompatdemo/MainActivity.java</strong></p><p><em>Note : As shown in the highlighted line7, the activity should extend the class ActionBarActivity.</em></p><pre class="brush: java; highlight: [6,7]; title: ; notranslate">

package in.wptrafficanalyzer.actionbarcompatdemo;

import android.os.Bundle;
import android.view.Menu;

import android.support.v7.app.ActionBarActivity;
public class MainActivity extends ActionBarActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

</pre><hr
/><p><strong>6. Screenshot of the application</strong></p><div
id="attachment_8555" class="wp-caption aligncenter" style="width: 250px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/action_bar_compat_demo_screenshot.png"><img
class="size-full wp-image-8555" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/action_bar_compat_demo_screenshot.png" alt="Android application with ActionBar is shown" width="240" height="320" /></a><p
class="wp-caption-text">Figure 2 : Android application with ActionBar is shown</p></div><hr
/><p><strong>7. Download Source code</strong></p><p
style="text-align: center"></p><div
class='w3eden'><div
class="wpdm-link-tpl link-btn light" data-durl="http://wptrafficanalyzer.in/blog/?wpdmdl=9370" ><div
class="media"><div
class="pull-left"><img
class="wpdm_icon" src="http://wptrafficanalyzer.in/blog/wp-content/plugins/download-manager/file-type-icons/zip.png" onError='this.src="http://wptrafficanalyzer.in/blog/wp-content/plugins/download-manager/file-type-icons/_blank.png";' /></div><div
class="media-body"><strong
class="ptitle">Implementing Action Bar using ActionBarCompat support library in Android <span
class="label label-default" style="font-weight: 400;">564.88 KB</span></strong><div><strong><a
class='wpdm-download-link wpdm-download-locked [btnclass]' rel='noindex nofollow' href='http://wptrafficanalyzer.in/blog/?wpdmdl=9370'><i
class=''></i>Download Full Source Code</a></strong></div></div></div></div><div
style="clear: both"></div></div><hr
/><div><b>How to hire me?</b><br
/><img
style='float:left;padding:10px' src='http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/george_wpta.jpg'><p>I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in<br
/><br
/>You can hire me on hourly basis or on project basis for Android applications development.<br
/><br
/>For hiring me, please mail your requirements to info@wptrafficanalyzer.in.<br
/></p><p><i><u>My other blogs</u></i><br
/><a
href='http://store4js.blogspot.com/' rel='nofollow' target='_blank'>store4js.blogspot.com</a></p><hr
/><p
style='clear:both'></p></div>]]></content:encoded> <wfw:commentRss>http://wptrafficanalyzer.in/blog/implementing-action-bar-using-actionbarcompat-support-library-in-android/feed/</wfw:commentRss> <slash:comments>5</slash:comments> </item> <item><title>Android &#8211; Setting up ActionBarCompat support library in Eclipse</title><link>http://wptrafficanalyzer.in/blog/android-setting-up-actionbarcompat-support-library-in-eclipse/</link> <comments>http://wptrafficanalyzer.in/blog/android-setting-up-actionbarcompat-support-library-in-eclipse/#comments</comments> <pubDate>Thu, 25 Jul 2013 06:00:06 +0000</pubDate> <dc:creator>George Mathew</dc:creator> <category><![CDATA[Android]]></category> <category><![CDATA[actionbar]]></category> <category><![CDATA[actionbarcompat]]></category><guid
isPermaLink="false">http://wptrafficanalyzer.in/blog/?p=8523</guid> <description><![CDATA[This week, a new version of Android support library ( Revision 18 )  is released with a new library called appcompat under the package android.support.v7. This new library is available at &#60;path-to-android-sdk&#62;/extras/android/support/v7/appcompat . The new library facilitates users to implement action bar back up to Android 2.1 ( API Level 7 ) . This article, demonstrates how to setup the new ActionBarCompat support library in Eclipse. In this article, we are using Eclipse 4.2.0 with ADT plugin 22.0.1. 1. Ensure to have the latest version of Android Support Library 2. Create new Android Project from existing code 3. Browse the directory appcompat from &#60;path-to-android-sdk&#62;/extras/android/support/v7 and click finish 4. Now, a new project is created as &#8220;android-support-v7-appcompat&#8221; 5. Setup JavaBuild Path Right click the project &#8220;android-support-v7-appcompat&#8221; and click &#8220;Properties&#8221; Select &#8220;Java Build Path&#8221; Open the tab &#8220;Order and Export&#8221; Tick &#8220;Android Private Libraries&#8221; and click OK 6. Clean and Build the project 7. Ready to use Now the ActionBarCompat library is ready to use for implementing action bar in Android applications. 8. What is next? Now we need to test the working of this library. For this please follow the article titled &#8220;Implementing Action Bar using ActionBarCompat support library in Android&#8221; How [&#8230;]]]></description> <content:encoded><![CDATA[<p>This week, a new version of Android support library ( Revision 18 )  is released with a new library called <em><strong>appcompat</strong></em> under the package android.support.v7. This new library is available at <em>&lt;path-to-android-sdk&gt;/extras/android/support/v7/appcompat .</em></p><p
style="text-align: center"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <ins
class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-0084597063187020"
data-ad-slot="4112080501"></ins><script>(adsbygoogle=window.adsbygoogle||[]).push({});</script></p><p>The new library facilitates users to implement action bar back up to Android 2.1 ( API Level 7 ) .</p><p>This article, demonstrates how to setup the new ActionBarCompat support library in Eclipse.</p><p>In this article, we are using Eclipse 4.2.0 with ADT plugin 22.0.1.</p><p
style="text-align: center"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <ins
class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-0084597063187020"
data-ad-slot="3824266707"></ins><script>(adsbygoogle=window.adsbygoogle||[]).push({});</script></p><hr
/><p><strong>1. Ensure to have the latest version of Android Support Library</strong></p><div
id="attachment_8525" class="wp-caption aligncenter" style="width: 460px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/action_bar_compat_setup_check.png"><img
class="size-full wp-image-8525" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/action_bar_compat_setup_check.png" alt="Ensure, Android Support Library Revision 18 or above is installed" width="450" height="280" /></a><p
class="wp-caption-text">Figure 1 : Ensure, Android Support Library Revision 18 or above is installed</p></div><hr
/><p><strong>2. Create new Android Project from existing code</strong></p><div
id="attachment_8527" class="wp-caption aligncenter" style="width: 460px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/action_bar_compat_setup_new_android_project.png"><img
class="size-full wp-image-8527" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/action_bar_compat_setup_new_android_project.png" alt="Create new Android project from existing code" width="450" height="402" /></a><p
class="wp-caption-text">Figure 2 : Create new Android project from existing code</p></div><hr
/><p><strong>3. Browse the directory appcompat from &lt;path-to-android-sdk&gt;/extras/android/support/v7 and click finish</strong></p><div
id="attachment_8528" class="wp-caption aligncenter" style="width: 460px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/action_bar_compat_setup_browser.png"><img
class="size-full wp-image-8528" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/action_bar_compat_setup_browser.png" alt="Browse the directory containing the library appcompat" width="450" height="394" /></a><p
class="wp-caption-text">Figure 3 : Browse the directory containing the library appcompat</p></div><hr
/><p><strong>4. Now, a new project is created as &#8220;android-support-v7-appcompat&#8221;</strong></p><hr
/><p><strong>5. Setup JavaBuild Path</strong></p><ul><li>Right click the project &#8220;android-support-v7-appcompat&#8221; and click &#8220;Properties&#8221;</li><li>Select &#8220;Java Build Path&#8221;</li><li>Open the tab &#8220;Order and Export&#8221;</li><li>Tick &#8220;Android Private Libraries&#8221; and click OK</li></ul><div
id="attachment_8529" class="wp-caption aligncenter" style="width: 460px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/action_bar_compat_setup_order_export.png"><img
class="size-full wp-image-8529" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/action_bar_compat_setup_order_export.png" alt="Tick Android Private Libraries" width="450" height="319" /></a><p
class="wp-caption-text">Figure 4 : Tick Android Private Libraries</p></div><hr
/><p><strong>6. Clean and Build the project</strong></p><div
id="attachment_8530" class="wp-caption aligncenter" style="width: 460px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/action_bar_compat_setup_clean_build.png"><img
class="size-full wp-image-8530" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/action_bar_compat_setup_clean_build.png" alt="Clean and Build the project &quot;android-support-v7-appcompat&quot;" width="450" height="367" /></a><p
class="wp-caption-text">Figure 5 : Clean and Build the project &quot;android-support-v7-appcompat&quot;</p></div><hr
/><p
style="text-align: left"><strong>7. Ready to use</strong></p><p
style="text-align: center"></p><p>Now the ActionBarCompat library is ready to use for implementing action bar in Android applications.</p><hr
/><p><strong>8. What is next?</strong></p><p>Now we need to test the working of this library. For this please follow the article titled &#8220;<a
title="Implementing Action Bar using ActionBarCompat support library in Android" href="http://wptrafficanalyzer.in/blog/implementing-action-bar-using-actionbarcompat-support-library-in-android" target="_blank">Implementing Action Bar using ActionBarCompat support library in Android</a>&#8221;</p><hr
/><div><b>How to hire me?</b><br
/><img
style='float:left;padding:10px' src='http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/george_wpta.jpg'><p>I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in<br
/><br
/>You can hire me on hourly basis or on project basis for Android applications development.<br
/><br
/>For hiring me, please mail your requirements to info@wptrafficanalyzer.in.<br
/></p><p><i><u>My other blogs</u></i><br
/><a
href='http://store4js.blogspot.com/' rel='nofollow' target='_blank'>store4js.blogspot.com</a></p><hr
/><p
style='clear:both'></p></div>]]></content:encoded> <wfw:commentRss>http://wptrafficanalyzer.in/blog/android-setting-up-actionbarcompat-support-library-in-eclipse/feed/</wfw:commentRss> <slash:comments>3</slash:comments> </item> <item><title>Android SearchView widget with Google Places API using ActionBarSherlock library</title><link>http://wptrafficanalyzer.in/blog/android-searchview-widget-with-google-places-api-using-actionbarsherlock-library/</link> <comments>http://wptrafficanalyzer.in/blog/android-searchview-widget-with-google-places-api-using-actionbarsherlock-library/#comments</comments> <pubDate>Thu, 18 Jul 2013 00:08:56 +0000</pubDate> <dc:creator>George Mathew</dc:creator> <category><![CDATA[Android]]></category> <category><![CDATA[action bar]]></category> <category><![CDATA[content provider]]></category> <category><![CDATA[CursorLoader]]></category> <category><![CDATA[Google Map]]></category> <category><![CDATA[Google Map Android API V2]]></category> <category><![CDATA[loader]]></category> <category><![CDATA[map]]></category> <category><![CDATA[searchview widget]]></category> <category><![CDATA[sherlock]]></category> <category><![CDATA[SherlockFragmentActivity]]></category> <category><![CDATA[SupportMapFragment]]></category><guid
isPermaLink="false">http://wptrafficanalyzer.in/blog/?p=8422</guid> <description><![CDATA[In this article, we will develop an Android application that can search Google Places API using SearchView widget and show the results in Google Maps Android API V2. In this application the searchview widget is placed in action bar. We know that, the SearchView widget is available only since Android API level 11. So will use ActionBarSherlock library for the backward compatibility. Major files used in this application are listed below : MainActivity.java : The search action is placed in the action bar of the MainActivity. searchable.xml : This is the configuration file for search dialog which defines content provider and suggestion properties. PlaceProvider.java : The content provider for fetching places from Google places autocomplete API. PlaceJSONParser.java : Parses the result of Google Places Autocomplete API. PlaceDetailsJSONParser.java : Parses the result of Google Places Details API. This application is developed in Eclipse (4.2.1) with ADT plugin (22.0.1) and Android SDK (22.0.1) and tested in real devices with Android versions 2.3.6  ( GingerBread ) and 4.1.2 ( Jelly Bean ). An alternative to this application is available in &#8220;Adding Google Places Autocomplete API as custom suggestions in Android Search Dialog&#8220;, where we have used SearchDialog window for searching places. 1. Create new Android application project [&#8230;]]]></description> <content:encoded><![CDATA[<p>In this article, we will develop an Android application that can search Google Places API using SearchView widget and show the results in Google Maps Android API V2. In this application the searchview widget is placed in action bar.</p><p>We know that, the SearchView widget is available only since Android API level 11. So will use ActionBarSherlock library for the backward compatibility.</p><p
style="text-align: center"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <ins
class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-0084597063187020"
data-ad-slot="4112080501"></ins><script>(adsbygoogle=window.adsbygoogle||[]).push({});</script></p><p>Major files used in this application are listed below :</p><ul><li>MainActivity.java : The search action is placed in the action bar of the MainActivity.</li></ul><ul><li><em>searchable.xml</em> : This is the configuration file for search dialog which defines content provider and suggestion properties.</li></ul><ul><li><em>PlaceProvider.java </em>: The content provider for fetching places from Google places autocomplete API.</li></ul><ul><li><em>PlaceJSONParser.java </em>: Parses the result of Google Places Autocomplete API.</li></ul><ul><li><em>PlaceDetailsJSONParser.java </em>: Parses the result of Google Places Details API.</li></ul><div
style="text-align: center"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <ins
class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-0084597063187020"
data-ad-slot="3824266707"></ins><script>(adsbygoogle=window.adsbygoogle||[]).push({});</script></div><p>This application is developed in Eclipse (4.2.1) with ADT plugin (22.0.1) and Android SDK (22.0.1) and tested in real devices with Android versions 2.3.6  ( GingerBread ) and 4.1.2 ( Jelly Bean ).</p><p>An alternative to this application is available in &#8220;<a
title="Adding Google Places Autocomplete API as custom suggestions in Android Search Dialog" href="http://wptrafficanalyzer.in/blog/adding-google-places-autocomplete-api-as-custom-suggestions-in-android-search-dialog" rel="nofollow" target="_blank">Adding Google Places Autocomplete API as custom suggestions in Android Search Dialog</a>&#8220;, where we have used SearchDialog window for searching places.</p><hr
/><p><strong>1. Create new Android application project</strong></p><p>Application Name : LocationSherlockSearchViewMapV2</p><p>Project Name : LocationSherlockSearchViewMapV2</p><p>Package Name : in.wptrafficanalyzer.locationsherlocksearchviewmapv2</p><p>Minimum Required SDK : API 8 : Android 2.2 ( Froyo )</p><p>Target SDK : API 17 : Android 4.2 ( Jelly Bean )</p><hr
/><p><strong>2. Delete Android Support library from this project</strong></p><p>In this application, we are using ActionBarSherlock library for the backward compatibility support of Android versions. Since ActionBarSherlock library already contains the Android Support library, we have to delete the Android Support Library (android-support-v4.jar)  from this project, if it is added automatically by Eclipse IDE.</p><p>We can delete the library file at libs/android-support-v4.jar .</p><hr
/><p><strong>3. Setup ActionBarSherlock library in Eclipse</strong></p><p>In order to setup ActionBarSherlock library, please refer the article titled &#8220;<a
title="Setting up Action Bar Sherlock Library 4.3.1 for Eclipse IDE" href="http://wptrafficanalyzer.in/blog/setting-up-action-bar-sherlock-library-4-3-1-for-eclipse-ide" rel="nofollow" target="_blank">Setting up Action Bar Sherlock Library 4.3.1 for Eclipse IDE</a>&#8221;</p><hr
/><p><strong>4. Clean and Build ActionBarSherlock library project in Eclipse</strong></p><div
id="attachment_8446" class="wp-caption aligncenter" style="width: 460px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/location_sherlock_searchview_mapv2_clean.png"><img
class="size-full wp-image-8446" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/location_sherlock_searchview_mapv2_clean.png" alt="Clean and Build ActionBarSherlock library project" width="450" height="369" /></a><p
class="wp-caption-text">Figure 1 : Clean and Build ActionBarSherlock library project</p></div><hr
/><p><strong>5. Link this project to ActionBarSherlock library</strong></p><div
id="attachment_8447" class="wp-caption aligncenter" style="width: 460px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/location_sherlock_searchview_mapv2_link_abs.png"><img
class="size-full wp-image-8447" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/location_sherlock_searchview_mapv2_link_abs.png" alt="Link this project to ActionBarSherlock library" width="450" height="455" /></a><p
class="wp-caption-text">Figure 2 : Link this project to ActionBarSherlock library</p></div><hr
/><p><strong>6. Download and configure Google Play Services Library in Eclipse</strong></p><p>Please follow the given below link to setup Google Play Service library in Eclipse.</p><p><a
title="http://developer.android.com/google/play-services/setup.html" href="http://developer.android.com/google/play-services/setup.html" rel="nofollow" target="_blank">http://developer.android.com/google/play-services/setup.html</a></p><hr
/><p><strong>7. Link this project to Google Play Service library</strong></p><div
id="attachment_8448" class="wp-caption aligncenter" style="width: 460px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/location_sherlock_searchview_mapv2_link_play.png"><img
class="size-full wp-image-8448" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/location_sherlock_searchview_mapv2_link_play.png" alt="Link this project to Google Play Service Library " width="450" height="455" /></a><p
class="wp-caption-text">Figure 3 : Link this project to Google Play Service Library</p></div><hr
/><p><strong>8. Get the API key for Google Maps Android API V2</strong></p><p>We need to get an API key from Google to use Google Maps in Android application.</p><p>Please follow the given below link to get the API key for Google Maps Android API v2.</p><p><a
href="https://developers.google.com/maps/documentation/android/start" rel="nofollow" target="_blank">https://developers.google.com/maps/documentation/android/start</a></p><hr
/><p><strong>9. Get the API key for Google Places API</strong></p><p>We can create API key for Google Place API by clicking &#8220;Create new Browser key&#8221;  available at the &#8220;API Access&#8221; pane of the Google console URL : <a
title="http://code.google.com/apis/console" href="http://code.google.com/apis/console" rel="nofollow" target="_blank">http://code.google.com/apis/console</a>.</p><p>Also ensure that, &#8220;<strong>Places API</strong>&#8221; is enabled in the &#8220;Services&#8221; pane of the Google console.</p><hr
/><p><strong>10. Update the file res/values/strings.xml</strong></p><pre class="brush: xml; highlight: [4,7,8,9]; title: ; 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;SearchView Demo&lt;/string&gt;
    &lt;string name=&quot;action_settings&quot;&gt;Settings&lt;/string&gt;
    &lt;string name=&quot;hello_world&quot;&gt;Hello world!&lt;/string&gt;
    &lt;string name=&quot;action_search&quot;&gt;Search&lt;/string&gt;
    &lt;string name=&quot;search_hint&quot;&gt;Search Places&lt;/string&gt;
    &lt;string name=&quot;search_settings&quot;&gt;Search Places&lt;/string&gt;

&lt;/resources&gt;

</pre><hr
/><p><strong>11. Update the layout file res/layout/activity_main.xml</strong></p><pre class="brush: xml; highlight: [7,8,9,10]; title: ; notranslate">

&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    tools:context=&quot;.MainActivity&quot; &gt;

    &lt;fragment
        android:id=&quot;@+id/map&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot; /&gt;

&lt;/RelativeLayout&gt;

</pre><hr
/><p><strong>12. Update the menu file res/menu/main.xml</strong></p><pre class="brush: xml; highlight: [3,4,5,6,7,8]; title: ; notranslate">

&lt;menu xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; &gt;

    &lt;item
        android:id=&quot;@+id/action_search&quot;
        android:orderInCategory=&quot;100&quot;
        android:showAsAction=&quot;ifRoom&quot;
        android:title=&quot;@string/action_search&quot;
        android:actionViewClass=&quot;com.actionbarsherlock.widget.SearchView&quot;/&gt;

    &lt;item
        android:id=&quot;@+id/action_settings&quot;
        android:orderInCategory=&quot;100&quot;
        android:showAsAction=&quot;never&quot;
        android:title=&quot;@string/action_settings&quot;/&gt;

&lt;/menu&gt;

</pre><hr
/><p><strong>13. Create the class file src/in/wptrafficanalyzer/locationsherlocksearchviewmapv2/PlaceJSONParser.java</strong></p><pre class="brush: java; highlight: [18,19,37,38,39,64,65,66]; title: ; notranslate">
package in.wptrafficanalyzer.locationsherlocksearchviewmapv2;

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

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class PlaceJSONParser {

    /** Receives a JSONObject and returns a list */
    public List&lt;HashMap&lt;String,String&gt;&gt; parse(JSONObject jObject){

        JSONArray jPlaces = null;
        try {
            /** Retrieves all the elements in the 'places' array */
            jPlaces = jObject.getJSONArray(&quot;predictions&quot;);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        /** Invoking getPlaces with the array of json object
        * where each json object represent a place
        */
        return getPlaces(jPlaces);
    }

    private List&lt;HashMap&lt;String, String&gt;&gt; getPlaces(JSONArray jPlaces){
        int placesCount = jPlaces.length();
        List&lt;HashMap&lt;String, String&gt;&gt; placesList = new ArrayList&lt;HashMap&lt;String,String&gt;&gt;();
        HashMap&lt;String, String&gt; place = null;

        /** Taking each place, parses and adds to list object */
        for(int i=0; i&lt;placesCount;i++){
            try {
                /** Call getPlace with place JSON object to parse the place */
                place = getPlace((JSONObject)jPlaces.get(i));
                placesList.add(place);

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

        return placesList;
    }

    /** Parsing the Place JSON object */
    private HashMap&lt;String, String&gt; getPlace(JSONObject jPlace){

        HashMap&lt;String, String&gt; place = new HashMap&lt;String, String&gt;();

        String id=&quot;&quot;;
        String reference=&quot;&quot;;
        String description=&quot;&quot;;

        try {

            description = jPlace.getString(&quot;description&quot;);
            id = jPlace.getString(&quot;id&quot;);
            reference = jPlace.getString(&quot;reference&quot;);

            place.put(&quot;description&quot;, description);
            place.put(&quot;_id&quot;,id);
            place.put(&quot;reference&quot;,reference);

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

</pre><hr
/><p><strong>14. Create the class file src/in/wptrafficanalyzer/locationsherlocksearchviewmapv2/PlaceDetailsJSONParser.java</strong></p><pre class="brush: java; highlight: [33,34,35]; title: ; notranslate">
package in.wptrafficanalyzer.locationsherlocksearchviewmapv2;

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

import org.json.JSONException;
import org.json.JSONObject;

public class PlaceDetailsJSONParser {

    /** Receives a JSONObject and returns a list */
    public List&lt;HashMap&lt;String,String&gt;&gt; parse(JSONObject jObject){

        Double lat = Double.valueOf(0);
        Double lng = Double.valueOf(0);
        String formattedAddress = &quot;&quot;;

        HashMap&lt;String, String&gt; hm = new HashMap&lt;String, String&gt;();
        List&lt;HashMap&lt;String, String&gt;&gt; list = new ArrayList&lt;HashMap&lt;String,String&gt;&gt;();

        try {
            lat = (Double)jObject.getJSONObject(&quot;result&quot;).getJSONObject(&quot;geometry&quot;).getJSONObject(&quot;location&quot;).get(&quot;lat&quot;);
            lng = (Double)jObject.getJSONObject(&quot;result&quot;).getJSONObject(&quot;geometry&quot;).getJSONObject(&quot;location&quot;).get(&quot;lng&quot;);
            formattedAddress = (String) jObject.getJSONObject(&quot;result&quot;).get(&quot;formatted_address&quot;);

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

        hm.put(&quot;lat&quot;, Double.toString(lat));
        hm.put(&quot;lng&quot;, Double.toString(lng));
        hm.put(&quot;formatted_address&quot;,formattedAddress);

        list.add(hm);

        return list;
    }
}
</pre><hr
/><p><strong>15. Create the file src/in/wptrafficanalyzer/locationsherlocksearchviewmapv2/PlaceProvider.java</strong></p><pre class="brush: java; highlight: [30,32,38,39,41,42,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,109,110,140,141,164,165,212,213,257,258,282,283,292,293,304]; title: ; notranslate">
package in.wptrafficanalyzer.locationsherlocksearchviewmapv2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.util.Log;

public class PlaceProvider extends ContentProvider {

    public static final String AUTHORITY = &quot;in.wptrafficanalyzer.locationsherlocksearchviewmapv2.PlaceProvider&quot;;

    public static final Uri SEARCH_URI = Uri.parse(&quot;content://&quot;+AUTHORITY+&quot;/search&quot;);

    public static final Uri DETAILS_URI = Uri.parse(&quot;content://&quot;+AUTHORITY+&quot;/details&quot;);

    private static final int SEARCH = 1;
    private static final int SUGGESTIONS = 2;
    private static final int DETAILS = 3;

    // Obtain browser key from https://code.google.com/apis/console
    String mKey = &quot;key=YOUR_BROWSER_KEY&quot;;

    // Defines a set of uris allowed with this content provider
    private static final UriMatcher mUriMatcher = buildUriMatcher();

    private static UriMatcher buildUriMatcher() {

        UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

        // URI for &quot;Go&quot; button
        uriMatcher.addURI(AUTHORITY, &quot;search&quot;, SEARCH );

        // URI for suggestions in Search Dialog
        uriMatcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY,SUGGESTIONS);

        // URI for Details
        uriMatcher.addURI(AUTHORITY, &quot;details&quot;,DETAILS);

        return uriMatcher;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
        String[] selectionArgs, String sortOrder) {
        Cursor c = null;

        PlaceJSONParser parser = new PlaceJSONParser();
        PlaceDetailsJSONParser detailsParser = new PlaceDetailsJSONParser();

        String jsonString = &quot;&quot;;
        String jsonPlaceDetails = &quot;&quot;;

        List&lt;HashMap&lt;String, String&gt;&gt; list = null;
        List&lt;HashMap&lt;String, String&gt;&gt; detailsList = null;

        MatrixCursor mCursor = null;

        switch(mUriMatcher.match(uri)){
        case SEARCH:
            // Defining a cursor object with columns description, lat and lng
            mCursor = new MatrixCursor(new String[] { &quot;description&quot;,&quot;lat&quot;,&quot;lng&quot; });

            // Create a parser object to parse places in JSON format
            parser = new PlaceJSONParser();

            // Create a parser object to parse place details in JSON format
            detailsParser = new PlaceDetailsJSONParser();

            // Get Places from Google Places API
            jsonString = getPlaces(selectionArgs);
            try {
                // Parse the places ( JSON =&gt; List )
                list = parser.parse(new JSONObject(jsonString));

                // Finding latitude and longitude for each places using Google Places Details API
                for(int i=0;i&lt;list.size();i++){
                    HashMap&lt;String, String&gt; hMap = (HashMap&lt;String, String&gt;) list.get(i);

                    detailsParser =new PlaceDetailsJSONParser();

                    // Get Place details
                    jsonPlaceDetails = getPlaceDetails(hMap.get(&quot;reference&quot;));

                    // Parse the details ( JSON =&gt; List )
                    detailsList = detailsParser.parse(new JSONObject(jsonPlaceDetails));

                    // Creating cursor object with places
                    for(int j=0;j&lt;detailsList.size();j++){
                        HashMap&lt;String, String&gt; hMapDetails = detailsList.get(j);

                        // Adding place details to cursor
                        mCursor.addRow(new String[]{ hMap.get(&quot;description&quot;) , hMapDetails.get(&quot;lat&quot;) , hMapDetails.get(&quot;lng&quot;) });
                    }

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

        case SUGGESTIONS :

            // Defining a cursor object with columns id, SUGGEST_COLUMN_TEXT_1, SUGGEST_COLUMN_INTENT_EXTRA_DATA
            mCursor = new MatrixCursor(new String[] { &quot;_id&quot;, SearchManager.SUGGEST_COLUMN_TEXT_1, SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA } );

            // Creating a parser object to parse places in JSON format
            parser = new PlaceJSONParser();

            // Get Places from Google Places API
            jsonString = getPlaces(selectionArgs);

            try {
                // Parse the places ( JSON =&gt; List )
                list = parser.parse(new JSONObject(jsonString));

                // Creating cursor object with places
                for(int i=0;i&lt;list.size();i++){
                    HashMap&lt;String, String&gt; hMap = (HashMap&lt;String, String&gt;) list.get(i);

                    // Adding place details to cursor
                    mCursor.addRow(new String[] { Integer.toString(i), hMap.get(&quot;description&quot;), hMap.get(&quot;reference&quot;) });
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            c = mCursor;
            break;

        case DETAILS :
            // Defining a cursor object with columns description, lat and lng
            mCursor = new MatrixCursor(new String[] { &quot;description&quot;,&quot;lat&quot;,&quot;lng&quot; });

            detailsParser = new PlaceDetailsJSONParser();
            jsonPlaceDetails = getPlaceDetails(selectionArgs[0]);
            try {
                detailsList = detailsParser.parse(new JSONObject(jsonPlaceDetails));
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            for(int j=0;j&lt;detailsList.size();j++){
                HashMap&lt;String, String&gt; hMapDetails = detailsList.get(j);
                mCursor.addRow(new String[]{ hMapDetails.get(&quot;formatted_address&quot;) , hMapDetails.get(&quot;lat&quot;) , hMapDetails.get(&quot;lng&quot;) });
            }
            c = mCursor;
            break;
        }
        return c;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public String getType(Uri uri) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean onCreate() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
        String[] selectionArgs) {
        // TODO Auto-generated method stub
        return 0;
    }

    /** A method to download json data from url */
    private String downloadUrl(String strUrl) throws IOException{
        String data = &quot;&quot;;
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try{
            URL url = new URL(strUrl);

            // Creating an http connection to communicate with url
            urlConnection = (HttpURLConnection) url.openConnection();

            // Connecting to url
            urlConnection.connect();

            // Reading data from url
            iStream = urlConnection.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

            StringBuffer sb = new StringBuffer();

            String line = &quot;&quot;;
            while( ( line = br.readLine()) != null){
                sb.append(line);
            }

            data = sb.toString();

            br.close();

        }catch(Exception e){
           Log.d(&quot;Exception while downloading url&quot;, e.toString());
        }finally{
            iStream.close();
            urlConnection.disconnect();
        }
        return data;
    }

    private String getPlaceDetailsUrl(String ref){

        // reference of place
        String reference = &quot;reference=&quot;+ref;

        // Sensor enabled
        String sensor = &quot;sensor=false&quot;;

        // Building the parameters to the web service
        String parameters = reference+&quot;&amp;&quot;+sensor+&quot;&amp;&quot;+mKey;

        // Output format
        String output = &quot;json&quot;;

        // Building the url to the web service
        String url = &quot;https://maps.googleapis.com/maps/api/place/details/&quot;+output+&quot;?&quot;+parameters;

        return url;
    }

    private String getPlacesUrl(String qry){

        try {
            qry = &quot;input=&quot; + URLEncoder.encode(qry, &quot;utf-8&quot;);
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        // Sensor enabled
        String sensor = &quot;sensor=false&quot;;

        // place type to be searched
        String types = &quot;types=geocode&quot;;

        // Building the parameters to the web service
        String parameters = qry+&quot;&amp;&quot;+types+&quot;&amp;&quot;+sensor+&quot;&amp;&quot;+mKey;

        // Output format
        String output = &quot;json&quot;;
        // Building the url to the web service
        String url = &quot;https://maps.googleapis.com/maps/api/place/autocomplete/&quot;+output+&quot;?&quot;+parameters;
        return url;
    }

    private String getPlaces(String[] params){
        // For storing data from web service
        String data = &quot;&quot;;
        String url = getPlacesUrl(params[0]);
        try{
            // Fetching the data from web service in background
            data = downloadUrl(url);
        }catch(Exception e){
            Log.d(&quot;Background Task&quot;,e.toString());
        }
        return data;
    }

    private String getPlaceDetails(String reference){
        String data = &quot;&quot;;
        String url = getPlaceDetailsUrl(reference);
        try {
            data = downloadUrl(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }
}
</pre><p><em>Note : Update &#8220;YOUR_BROWSER_KEY on line 39 with the browser key obtained in Step 9.</em></p><hr
/><p><strong>16. Update the class MainActivity in the file src/in/wptrafficanalyzer/locationsherlocksearchviewmapv2/MainActivity.java</strong></p><pre class="brush: java; highlight: [34,37,38,39,40,41,42,43,45,46,47,48,49,50,52,53,54,55,56,58,59,60,61,62,69,70,71,72,77,78,79,80,81,82,83,84,85,86,88,89,90,91,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113]; title: ; notranslate">

package in.wptrafficanalyzer.locationsherlocksearchviewmapv2;

import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.widget.SearchView;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends SherlockFragmentActivity implements LoaderCallbacks&lt;Cursor&gt;{

    GoogleMap mGoogleMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mGoogleMap = fragment.getMap();

        handleIntent(getIntent());
    }

    private void handleIntent(Intent intent){
        if(intent.getAction().equals(Intent.ACTION_SEARCH)){
            doSearch(intent.getStringExtra(SearchManager.QUERY));
        }else if(intent.getAction().equals(Intent.ACTION_VIEW)){
            getPlace(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        handleIntent(intent);
    }

    private void doSearch(String query){
        Bundle data = new Bundle();
        data.putString(&quot;query&quot;, query);
        getSupportLoaderManager().restartLoader(0, data, this);
    }

    private void getPlace(String query){
        Bundle data = new Bundle();
        data.putString(&quot;query&quot;, query);
        getSupportLoaderManager().restartLoader(1, data, this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getSupportMenuInflater().inflate(R.menu.main, menu);

        // Get the SearchView and set the searchable configuration
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

        return true;
    }

    @Override
    public Loader&lt;Cursor&gt; onCreateLoader(int arg0, Bundle query) {
        CursorLoader cLoader = null;
        if(arg0==0)
            cLoader = new CursorLoader(getBaseContext(), PlaceProvider.SEARCH_URI, null, null, new String[]{ query.getString(&quot;query&quot;) }, null);
        else if(arg0==1)
            cLoader = new CursorLoader(getBaseContext(), PlaceProvider.DETAILS_URI, null, null, new String[]{ query.getString(&quot;query&quot;) }, null);
        return cLoader;

    }

    @Override
    public void onLoadFinished(Loader&lt;Cursor&gt; arg0, Cursor c) {
        showLocations(c);
    }

    @Override
    public void onLoaderReset(Loader&lt;Cursor&gt; arg0) {
        // TODO Auto-generated method stub
    }

    private void showLocations(Cursor c){
        MarkerOptions markerOptions = null;
        LatLng position = null;
        mGoogleMap.clear();
        while(c.moveToNext()){
            markerOptions = new MarkerOptions();
            position = new LatLng(Double.parseDouble(c.getString(1)),Double.parseDouble(c.getString(2)));
            markerOptions.position(position);
            markerOptions.title(c.getString(0));
            mGoogleMap.addMarker(markerOptions);
        }
        if(position!=null){
            CameraUpdate cameraPosition = CameraUpdateFactory.newLatLng(position);
            mGoogleMap.animateCamera(cameraPosition);
        }
    }
}

</pre><hr
/><p><strong>17. Update the configuration file /res/xml/searchable.xml</strong></p><pre class="brush: xml; highlight: [7]; title: ; notranslate">

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;searchable xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:label=&quot;@string/app_name&quot;
    android:hint=&quot;@string/search_hint&quot;
    android:searchSettingsDescription=&quot;@string/search_settings&quot;

    android:searchSuggestAuthority=&quot;in.wptrafficanalyzer.locationsherlocksearchviewmapv2.PlaceProvider&quot;
    android:searchSuggestIntentAction=&quot;android.intent.action.VIEW&quot;
    android:searchSuggestSelection=&quot; ?&quot;
    android:searchSuggestThreshold=&quot;2&quot; &gt;

&lt;/searchable&gt;

</pre><hr
/><p><strong>18. Update the file AndroidManifest.xml</strong></p><pre class="brush: xml; highlight: [11,12,13,14,16,17,19,20,22,23,25,26,28,29,30,32,33,35,36,37,38,48,55,56,57,59,60,61,63,64,65,69,70,71,72,77]; title: ; 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;in.wptrafficanalyzer.locationsherlocksearchviewmapv2&quot;
    android:versionCode=&quot;1&quot;
    android:versionName=&quot;1.0&quot; &gt;

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

    &lt;!-- Protect the map component of the application using application signature --&gt;
    &lt;permission
        android:name=&quot;in.wptrafficanalyzer.locationsherlocksearchviewmapv2.permission.MAPS_RECEIVE&quot;
        android:protectionLevel=&quot;signature&quot; /&gt;

    &lt;!-- Allows to receive map --&gt;
    &lt;uses-permission android:name=&quot;in.wptrafficanalyzer.locationsherlocksearchviewmapv2.permission.MAPS_RECEIVE&quot; /&gt;

    &lt;!-- Used by the Google Maps Android API V2 to download map tiles from Google Maps servers --&gt;
    &lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;

    &lt;!-- Allows the Google Maps Android API V2 to cache map tile data in the device's external storage area --&gt;
    &lt;uses-permission android:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot; /&gt;

    &lt;!-- Allows the Google Maps Android API V2 to use WiFi or mobile cell data (or both) to determine the device's location --&gt;
    &lt;uses-permission android:name=&quot;android.permission.ACCESS_COARSE_LOCATION&quot; /&gt;

    &lt;!-- Allows the Google Maps Android API V2 to use the Global Positioning System (GPS)
    to determine the device's location to within a very small area --&gt;
    &lt;uses-permission android:name=&quot;android.permission.ACCESS_FINE_LOCATION&quot; /&gt;

    &lt;!-- Allows to contact Google Serves --&gt;
    &lt;uses-permission android:name=&quot;com.google.android.providers.gsf.permission.READ_GSERVICES&quot; /&gt;

    &lt;!-- Google Maps Android API V2 requires OpenGL ES version 2 --&gt;
    &lt;uses-feature
        android:glEsVersion=&quot;0x00020000&quot;
        android:required=&quot;true&quot; /&gt;

    &lt;application
        android:allowBackup=&quot;true&quot;
        android:icon=&quot;@drawable/ic_launcher&quot;
        android:label=&quot;@string/app_name&quot;
        android:theme=&quot;@style/Theme.Sherlock&quot; &gt;
        &lt;activity
            android:name=&quot;in.wptrafficanalyzer.locationsherlocksearchviewmapv2.MainActivity&quot;
            android:label=&quot;@string/app_name&quot;
            android:launchMode=&quot;singleTop&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;intent-filter&gt;
                &lt;action android:name=&quot;android.intent.action.SEARCH&quot; /&gt;
            &lt;/intent-filter&gt;

            &lt;!-- Points to searchable activity --&gt;
            &lt;meta-data android:name=&quot;android.app.default_searchable&quot;
                android:value=&quot;.MainActivity&quot; /&gt;

            &lt;!-- Points to searchable meta data --&gt;
            &lt;meta-data android:name=&quot;android.app.searchable&quot;
                android:resource=&quot;@xml/searchable&quot;/&gt;

        &lt;/activity&gt;

        &lt;provider
            android:name=&quot;.PlaceProvider&quot;
            android:authorities=&quot;in.wptrafficanalyzer.locationsherlocksearchviewmapv2.PlaceProvider&quot;
            android:exported=&quot;false&quot; /&gt;

        &lt;!-- Specifies the Android API Key, which is obtained from Google API Console --&gt;
        &lt;meta-data
            android:name=&quot;com.google.android.maps.v2.API_KEY&quot;
            android:value=&quot;YOUR_ANDROID_API_KEY&quot; /&gt;
    &lt;/application&gt;
&lt;/manifest&gt;

</pre><p><em>Note : Update &#8220;YOUR_ANDROID_API_KEY on line 77 with the browser key obtained in Step 8.</em></p><hr
/><p><strong>19. Screenshots of the application</strong></p><div
id="attachment_8451" class="wp-caption aligncenter" style="width: 250px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/location_sherlock_searchview_mapv2_main.png"><img
class="size-full wp-image-8451" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/location_sherlock_searchview_mapv2_main.png" alt="MainActivity of the application" width="240" height="320" /></a><p
class="wp-caption-text">Figure 4 : MainActivity of the application</p></div><div
id="attachment_8452" class="wp-caption aligncenter" style="width: 250px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/location_sherlock_searchview_mapv2_suggest.png"><img
class="size-full wp-image-8452" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/location_sherlock_searchview_mapv2_suggest.png" alt="Searching a place using SuggestView widget" width="240" height="320" /></a><p
class="wp-caption-text">Figure 5 : Searching a place using SuggestView widget</p></div><div
id="attachment_8453" class="wp-caption aligncenter" style="width: 250px"><a
href="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/location_sherlock_searchview_mapv2_showplace.png"><img
class="size-full wp-image-8453" src="http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/location_sherlock_searchview_mapv2_showplace.png" alt="Showing result in Google Maps Android API V2" width="240" height="320" /></a><p
class="wp-caption-text">Figure 6 : Showing result in Google Maps Android API V2</p></div><hr
/><p><strong>20. Download Source code</strong></p><p
style="text-align: center"></p><div
class='w3eden'><div
class="wpdm-link-tpl link-btn light" data-durl="http://wptrafficanalyzer.in/blog/?wpdmdl=9369" ><div
class="media"><div
class="pull-left"><img
class="wpdm_icon" src="http://wptrafficanalyzer.in/blog/wp-content/plugins/download-manager/file-type-icons/zip.png" onError='this.src="http://wptrafficanalyzer.in/blog/wp-content/plugins/download-manager/file-type-icons/_blank.png";' /></div><div
class="media-body"><strong
class="ptitle">Android SearchView widget with Google Places API using ActionBarSherlock library <span
class="label label-default" style="font-weight: 400;">128.70 KB</span></strong><div><strong><a
class='wpdm-download-link wpdm-download-locked [btnclass]' rel='noindex nofollow' href='http://wptrafficanalyzer.in/blog/?wpdmdl=9369'><i
class=''></i>Download Full Source Code</a></strong></div></div></div></div><div
style="clear: both"></div></div><hr
/><div><b>How to hire me?</b><br
/><img
style='float:left;padding:10px' src='http://wptrafficanalyzer.in/blog/wp-content/uploads/2013/07/george_wpta.jpg'><p>I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in<br
/><br
/>You can hire me on hourly basis or on project basis for Android applications development.<br
/><br
/>For hiring me, please mail your requirements to info@wptrafficanalyzer.in.<br
/></p><p><i><u>My other blogs</u></i><br
/><a
href='http://store4js.blogspot.com/' rel='nofollow' target='_blank'>store4js.blogspot.com</a></p><hr
/><p
style='clear:both'></p></div>]]></content:encoded> <wfw:commentRss>http://wptrafficanalyzer.in/blog/android-searchview-widget-with-google-places-api-using-actionbarsherlock-library/feed/</wfw:commentRss> <slash:comments>18</slash:comments> </item> </channel> </rss>