Sunday 28 April 2013

Name, Phone Number, Email Validation using Saripaar Example in Android

Download Saripaar Library from gitHub 


Add Saripaar Library Project to your project, (same method of adding actionbarsherlock to your project)

main.xml


<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="18dp"
            android:layout_marginTop="30dp"
            android:text="Name"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/name_add_edit_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignTop="@+id/textView1"
            android:ems="10" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/textView1"
            android:layout_below="@id/name_add_edit_text"
            android:layout_marginTop="60dp"
            android:text="IpAddress"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/ipaddress_edit_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/textView2"
            android:layout_alignBottom="@+id/textView2"
            android:layout_toRightOf="@+id/textView2"
            android:ems="10" />

        <CheckBox
            android:id="@+id/terms_conditions_checkbox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/textView2"
            android:layout_below="@id/ipaddress_edit_text"
            android:layout_marginTop="56dp"
            android:text="I accept terms and conditions" />

        <Button
            android:id="@+id/add_edit_done_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/terms_conditions_checkbox"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="27dp"
            android:text="SAVE" />

    </RelativeLayout>

PhoneNumberEmailValidationActivity.java

package com.rajeshvijayakumar.saripaar;

import com.mobsandgeeks.saripaar.Rule;
import com.mobsandgeeks.saripaar.Validator;
import com.mobsandgeeks.saripaar.Validator.ValidationListener;
import com.mobsandgeeks.saripaar.annotation.Email;
import com.mobsandgeeks.saripaar.annotation.NumberRule;
import com.mobsandgeeks.saripaar.annotation.NumberRule.NumberType;
import com.mobsandgeeks.saripaar.annotation.Required;
import com.mobsandgeeks.saripaar.annotation.TextRule;

public class PhoneNumberEmailValidationActivity extends Activity implements ValidationListener {

    @Required(order = 1)
    @TextRule(order = 2, minLength = 5, maxLength = 35, trim = true, message = "Enter Valid Full Name")
    private EditText mNameEditText;

    @Required(order = 3)
    @Email(order = 4, message = "Please Check and Enter a valid Email Address")
    private EditText mEmailEditText;

    @Required(order = 5)
    @NumberRule(order = 6, message = "Enter Phone Number in Numeric", type = NumberType.LONG)
    @TextRule(order = 7, message = "Enter valid Phone Number", minLength = 10, maxLength = 14)
    private EditText mPhoneNumberEditText;

    private Button mAddEditButton;
    private Validator mAddEditValidator;

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

        mNameEditText = (EditText) findViewById(R.id.name);
        mEmailEditText = (EditText) findViewById(R.id.email_address);
        mPhoneNumberEditText = (EditText) findViewById(R.id.phone_number);
        mAddEditButton = (Button) findViewById(R.id.validate_button);

        mAddEditButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                ((com.mobsandgeeks.saripaar.Validator) mAddEditValidator).validate();
            }
        });
        mAddEditValidator = new Validator(this);
        mAddEditValidator.setValidationListener(this);

    }

    @Override
    public void onFailure(View failedView, Rule<?> failedRule) {

        String message = failedRule.getFailureMessage();
        if (failedView instanceof EditText) {
            Toast.makeText(this, message,
                    Toast.LENGTH_SHORT).show();
        }  else {
            Toast.makeText(this, "Record Not Saved", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onSuccess() {
        Toast.makeText(this, "Record Saved Successfully", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onValidationCancelled() {
    }

    @Override
    public void preValidation() {
    }
}


Output: 






Source Code :  Download Example with Library






Sunday 21 April 2013

Alert Dialog : Dialog with Item List Example in Android

activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <Button
        android:id="@+id/done_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="DONE" />

</RelativeLayout>

MainActivity.java

package com.example.alertdialogex;

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

public class MainActivity extends Activity implements OnClickListener {

    private Button mDoneButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mDoneButton = (Button) findViewById(R.id.done_button);
        mDoneButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        final CharSequence[] items = {
                "Rajesh", "Mahesh", "Vijayakumar"
        };

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Make your selection");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                // Do something with the selection
                mDoneButton.setText(items[item]);
            }
        });
        AlertDialog alert = builder.create();
        alert.show();

    }
}

 Output :






















Action Bar Sherlock : Action Bar with Custom Title View Example in Android

 

Add ActionBarSherlock Library Project to your Application Project, Here is a Link for this

activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />

</RelativeLayout>


custom_action_layout.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#86898a"
    android:gravity="center_vertical" >

    <TextView
        android:id="@+id/title_text"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:text="My Title"
        android:textColor="#ffffff"
        android:textSize="20sp"
        android:textStyle="bold" />

</RelativeLayout>


MainActivity.java

package com.rajeshvijayakumar.customtitle;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;

public class MainActivity extends SherlockActivity {

    // Action bar
    private ActionBar mActionBar;
    private LayoutInflater mInflater;
    private View mCustomView;
    private TextView mTitleTextView;

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

    private void initActionBar() {
        mActionBar = getSupportActionBar();
        mActionBar.setDisplayShowHomeEnabled(false);
        mActionBar.setDisplayShowTitleEnabled(false);
        mInflater = LayoutInflater.from(this);
        mCustomView = mInflater.inflate(R.layout.custom_action_layout, null);
        mTitleTextView = (TextView) mCustomView.findViewById(R.id.title_text);
        mTitleTextView.setText("My Own Title");
        mActionBar.setCustomView(mCustomView);
        mActionBar.setDisplayShowCustomEnabled(true);
        // mActionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.at_header_bg));
    }
}

Output :


  


Sunday 14 April 2013

Xml Pull Parser Example in Android

rss_feed_view.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ListView
        android:id="@+id/rss_list_view"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</RelativeLayout>

rss_list_item.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/rss_title_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="17dp"
        android:layout_marginTop="14dp"
        android:text="NDTV"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="@android:color/black" />

</RelativeLayout>

RSSFeed.java


public class RSSFeed implements Serializable {

    private String title;
    private String link;
    private String description;
    private String category;
    private String pubDate;
    private String guid;
    private String feedburnerOrigLink;

    public RSSFeed() {
    }

    public RSSFeed(String title, String link, String description, String category, String pubDate,
            String guid, String feedburnerOrigLink) {
        this.title = title;
        this.link = link;
        this.description = description;
        this.category = category;
        this.pubDate = pubDate;
        this.guid = guid;
        this.feedburnerOrigLink = feedburnerOrigLink;
    }

    public String getTitle() {
        return title;
    }

    public String getLink() {
        return link;
    }

    public String getDescription() {
        return description;
    }

    public String getCategory() {
        return category;
    }

    public String getPubDate() {
        return pubDate;
    }

    public String getGuid() {
        return guid;
    }

    public String getFeedburnerOrigLink() {
        return feedburnerOrigLink;
    }


    public void setTitle(String title) {
        this.title = title;
    }

    public void setLink(String link) {
        this.link = link;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public void setPubDate(String pubDate) {
        this.pubDate = pubDate;
    }

    public void setGuid(String guid) {
        this.guid = guid;
    }

    public void setFeedburnerOrigLink(String feedburnerOrigLink) {
        this.feedburnerOrigLink = feedburnerOrigLink;
    }
}

NewsFeedParser.java

import com.rajeshvijayakumar.model.RSSFeed;

public class NewsFeedParser {
    private InputStream urlStream;
    private XmlPullParserFactory factory;
    private XmlPullParser parser;

    private List<RSSFeed> rssFeedList;
    private RSSFeed rssFeed;

    private String urlString;
    private String tagName;

    private String title;
    private String link;
    private String description;
    private String category;
    private String pubDate;
    private String guid;
    private String feedburner;

    public static final String ITEM = "item";
    public static final String CHANNEL = "channel";
   
    public static final String TITLE = "title";
    public static final String LINK = "link";
    public static final String DESCRIPTION = "description";
    public static final String CATEGORY = "category";
    public static final String PUBLISHEDDATE = "pubDate";
    public static final String GUID = "guid";
    public static final String FEEDBURNERORIGLINK = "feedburner:origLink";

   
    public NewsFeedParser(String urlString) {
        this.urlString = urlString;
    }

    public static InputStream downloadUrl(String urlString) throws IOException {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        conn.connect();
        InputStream stream = conn.getInputStream();
        return stream;
    }
   
    public List<RSSFeed> parse() {
        try {
            int count = 0;
            factory = XmlPullParserFactory.newInstance();
            parser = factory.newPullParser();
            urlStream = downloadUrl(urlString);
            parser.setInput(urlStream, null);
            int eventType = parser.getEventType();
            boolean done = false;
            rssFeed = new RSSFeed();
            rssFeedList = new ArrayList<RSSFeed>();
            while (eventType != XmlPullParser.END_DOCUMENT && !done) {
                tagName = parser.getName();

                switch (eventType) {
                    case XmlPullParser.START_DOCUMENT:
                        break;
                    case XmlPullParser.START_TAG:
                        if (tagName.equals(ITEM)) {
                            rssFeed = new RSSFeed();
                        }
                        if (tagName.equals(TITLE)) {
                            title = parser.nextText().toString();
                        }
                        if (tagName.equals(LINK)) {
                            link = parser.nextText().toString();
                        }
                        if (tagName.equals(DESCRIPTION)) {
                            description = parser.nextText().toString();
                        }
                        if (tagName.equals(CATEGORY)) {
                            category = parser.nextText().toString();
                        }
                        if (tagName.equals(PUBLISHEDDATE)) {
                            pubDate = parser.nextText().toString();
                        }
                        if (tagName.equals(GUID)) {
                            guid = parser.nextText().toString();
                        }
                        if (tagName.equals(FEEDBURNERORIGLINK)) {
                            feedburner = parser.nextText().toString();
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        if (tagName.equals(CHANNEL)) {
                            done = true;
                        } else if (tagName.equals(ITEM)) {
                            rssFeed = new RSSFeed(title, link, description, category, pubDate,                               guid,  feedburner);
                            rssFeedList.add(rssFeed);
                        }
                        break;
                }
                eventType = parser.next();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return rssFeedList;
    }
}

MainActivity.java


package com.rajeshvijayakumar.xmlpullparser;

import com.rajeshvijayakumar.model.RSSFeed;
import com.rajeshvijayakumar.parser.NewsFeedParser;

public class MainActivity extends Activity implements OnItemClickListener {

    private ListView mRssListView;
    private NewsFeedParser mNewsFeeder;
    private List<RSSFeed> mRssFeedList;
    private RssAdapter mRssAdap;

    private static final String TOPSTORIES =
            "http://feeds.feedburner.com/NdtvNews-TopStories?format=xml";

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

        mRssListView = (ListView) findViewById(R.id.rss_list_view);
        mRssFeedList = new ArrayList<RSSFeed>();
        new DoRssFeedTask().execute(TOPSTORIES);
        mRssListView.setOnItemClickListener(this);
    }

    private class RssAdapter extends ArrayAdapter<RSSFeed> {
        private List<RSSFeed> rssFeedLst;

        public RssAdapter(Context context, int textViewResourceId, List<RSSFeed> rssFeedLst) {
            super(context, textViewResourceId, rssFeedLst);
            this.rssFeedLst = rssFeedLst;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            View view = convertView;
            RssHolder rssHolder = null;
            if (convertView == null) {
                view = View.inflate(MainActivity.this, R.layout.rss_list_item, null);
                rssHolder = new RssHolder();
                rssHolder.rssTitleView = (TextView) view.findViewById(R.id.rss_title_view);
                view.setTag(rssHolder);
            } else {
                rssHolder = (RssHolder) view.getTag();
            }
            RSSFeed rssFeed = rssFeedLst.get(position);
            rssHolder.rssTitleView.setText(rssFeed.getTitle());
            return view;
        }
    }

    static class RssHolder {
        public TextView rssTitleView;
    }

    public class DoRssFeedTask extends AsyncTask<String, Void, List<RSSFeed>> {
        ProgressDialog prog;
        String jsonStr = null;
        Handler innerHandler;

        @Override
        protected void onPreExecute() {
            prog = new ProgressDialog(MainActivity.this);
            prog.setMessage("Loading....");
            prog.show();
        }

        @Override
        protected List<RSSFeed> doInBackground(String... params) {
            for (String urlVal : params) {
                mNewsFeeder = new NewsFeedParser(urlVal);
            }
            mRssFeedList = mNewsFeeder.parse();
            return mRssFeedList;
        }

        @Override
        protected void onPostExecute(List<RSSFeed> result) {
            prog.dismiss();
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    mRssAdap = new RssAdapter(MainActivity.this, R.layout.rss_list_item,
                            mRssFeedList);
                    int count = mRssAdap.getCount();
                    if (count != 0 && mRssAdap != null) {
                        mRssListView.setAdapter(mRssAdap);
                    }
                }
            });
        }

        @Override
        protected void onProgressUpdate(Void... values) {
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View v, int position, long id) {
    }
}
 Add this Permission in your Manifest.xml file of your project

   <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    

 Output :




Source Code : Download this Example Here


Alert Dialog Example in Android

main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/alert_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show ALert" />
           
</LinearLayout>

AlertDialogActivity.java

package com.rajeshvijayakumar.alertdialog;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class AlertDialogActivity extends Activity {
    private Button MButton;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mButton = (Button) findViewById(R.id.alert_button);

        mButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(               AlertDialogActivity.this);
                alertDialogBuilder.setTitle("Close");
                alertDialogBuilder
                        .setMessage("Click Ok to Close Application")
                        .setCancelable(false)
                        .setPositiveButton("Ok",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                            int id) {
                                        finish();
                                    }
                                })
                        .setNegativeButton("Cancel",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                            int id) {
                                        dialog.cancel();
                                    }
                                });
                AlertDialog alertDialog = alertDialogBuilder.create();
                alertDialog.show();
            }
        });
    }
}


Output :








Source Code : Download this Example Here


Thursday 11 April 2013

Alternative to Custom Adapter : Instant Adapter Example in Android

Get Instant Adapter Library from the following Url : https://github.com/ragunathjawahar/instant-adapter

Import and Add Instant library Project to your Project as shown below :





Then use the following code :

In activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ListView
        android:id="@+id/person_list_view"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</RelativeLayout>


In list_item.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="14dp"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/phone_no"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@id/name"
        android:layout_marginLeft="47dp"
        android:layout_toRightOf="@id/name"
        android:text="Small Text"
        android:textAppearance="?android:attr/textAppearanceSmall" />

    <TextView
        android:id="@+id/email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@id/phone_no"
        android:layout_below="@id/name"
        android:text="Small Text"
        android:textAppearance="?android:attr/textAppearanceSmall" />

</RelativeLayout>


Create Person.java Model

package com.rajeshvijayakumar.model;

import com.mobsandgeeks.adapters.InstantText;
import com.rajeshvijayakumar.insta.R;

public class Person {

    private String name;
    private String phoneNo;
    private String emailId;

    public Person(String name, String phoneNo, String emailId) {
        this.name = name;
        this.phoneNo = phoneNo;
        this.emailId = emailId;
    }

    @InstantText(viewId = R.id.name)
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @InstantText(viewId = R.id.phone_no, formatString = "Mob : %s")
    public String getPhoneNo() {
        return phoneNo;
    }

    public void setPhoneNo(String phoneNo) {
        this.phoneNo = phoneNo;
    }

    @InstantText(viewId = R.id.email, formatString = "Email : %s")
    public String getEmailId() {
        return emailId;
    }

    public void setEmailId(String emailId) {
        this.emailId = emailId;
    }
}


MainActivity.java

package com.rajeshvijayakumar.insta;

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

import com.mobsandgeeks.adapters.InstantAdapter;
import com.rajeshvijayakumar.model.Person;

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

public class MainActivity extends Activity {

    private ListView mPersonListView;
    private InstantAdapter mInsAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mPersonListView = (ListView) findViewById(R.id.person_list_view);
        mInsAdapter = new InstantAdapter<Person>(this, R.layout.list_item, Person.class, getPersons());
        mPersonListView.setAdapter(mInsAdapter);
    }

    private List<Person> getPersons() {

        List<Person> persons = new ArrayList<Person>();
        persons.add(new Person("Rajesh", "9600272370", "rajesh@gmail.com"));
        persons.add(new Person("Kuberan", "3224231223", "kuberan@gmail.com"));
        persons.add(new Person("Ramanan", "9873272323", "ramanan@gmail.com"));
        persons.add(new Person("Kalidasan", "9723476322", "kali@gmail.com"));

        return persons;
    }
}


Output :


Source Code :  Download this example here

Sunday 7 April 2013

Location Manager: Getting User Current Location using GPS Example in Android

main.xml

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/gps_text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
</LinearLayout>

CurrentLocationActivity.java


package com.rajeshvijayakumar.gps;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class CurrentLocationActivity extends Activity {

    /** Called when the activity is first created. */

    private TextView gpsLocationView;
    private List<Address> addresses;
    private    String text;
    @Override

    public void onCreate(Bundle savedInstanceState)    {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);
    gpsLocationView=(TextView) findViewById(R.id.gps_text);
    /* Use the LocationManager class to obtain GPS locations */
    LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    LocationListener mlocListener = new MyLocationListener();
    mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
    }

    /* Class My Location Listener */
    public class MyLocationListener implements LocationListener    {

        @Override
        public void onLocationChanged(Location loc){
            loc.getLatitude();
            loc.getLongitude();
            Geocoder gcd = new Geocoder(getApplicationContext(), Locale.getDefault());
             try {
                addresses = gcd.getFromLocation(loc.getLatitude(),loc.getLongitude(), 1);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            String text=(addresses!=null)?"City : "+addresses.get(0).getSubLocality()+"\n Country : "+addresses.get(0).getCountryName():"Unknown Location";

            String locationValue = "My current location is: "+ text;
            gpsLocationView.setText(locationValue);
        }

        @Override
        public void onProviderDisabled(String provider){
            Toast.makeText( getApplicationContext(),"Gps Disabled",Toast.LENGTH_SHORT ).show();
        }

        @Override
        public void onProviderEnabled(String provider){
            Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras){
            }
    }
}


Source code :  Download this example