Android Maps Using Google Maps API V2

Since end of last year, Google launch Google Map API V2, so for Android programmer there's a new way to code about Map. In Google Map API V1 we just need a MapActivity, so on the V2 there's a different way to call the Map API.

Beofre starting your project, you must install Google Play Service from your Android SDK, and then import the Google Play Service Library to your project directory, If you don't do this step you can't import all com.google.android.xxx.

Here's same sample code to using Map on your Android Project.


 package com.ademahendramap;
  
 import java.util.List;  
 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.BitmapDescriptorFactory;  
 import com.google.android.gms.maps.model.LatLng;  
 import com.google.android.gms.maps.model.Marker;  
 import com.google.android.gms.maps.model.MarkerOptions;  
 import com.google.android.gms.maps.model.PolylineOptions;  
 import android.content.Context;  
 import android.content.Intent;  
 import android.graphics.Color;  
 import android.location.Criteria;  
 import android.location.Location;  
 import android.location.LocationListener;  
 import android.location.LocationManager;  
 import android.os.Bundle;  
 import android.provider.Settings;  
 import android.support.v4.app.FragmentActivity;  
 import android.util.Log;  
 import android.widget.Toast;  

 public class MapDirection extends FragmentActivity implements LocationListener {  
   private GoogleMap map;  
   private static final LatLng Malang = new LatLng(-7.955888,112.63481);  
   private LocationManager locationManager;  
   private String provider;  

   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.map_direction);  
      
     map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();  
     LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);  
     boolean enabledGPS = service  
         .isProviderEnabled(LocationManager.GPS_PROVIDER);  
     boolean enabledWiFi = service  
         .isProviderEnabled(LocationManager.NETWORK_PROVIDER);  
     // Check if enabled and if not send user to the GSP settings  
     // Better solution would be to display a dialog and suggesting to   
     // go to the settings  
     if (!enabledGPS) {  
       Toast.makeText(this, "GPS signal not found", Toast.LENGTH_LONG).show();  
       Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);  
       startActivity(intent);  
     }  
     locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);  
     // Define the criteria how to select the locatioin provider -> use  
     // default  
     Criteria criteria = new Criteria();  
     provider = locationManager.getBestProvider(criteria, false);  
     Location location = locationManager.getLastKnownLocation(provider);  
     // Initialize the location fields  
     if (location != null) {  
       Toast.makeText(this, "Current Provider " + provider,  
           Toast.LENGTH_SHORT).show();  
       onLocationChanged(location);  
     } else {  
       //do something  
     }  
   }  
 
   @Override  
   protected void onResume() {  
     super.onResume();  
     locationManager.requestLocationUpdates(provider, 400, 1, this);  
   }  

   @Override  
   protected void onPause() {  
     super.onPause();  
// Remove update of location listener
     locationManager.removeUpdates(this);  
   }  
   @Override  
   public void onLocationChanged(Location location) {  
     double lat = location.getLatitude();  
     double lng = location.getLongitude();  
  
     LatLng coordinate = new LatLng(lat, lng);  
      
     Marker startposition = map.addMarker(new MarkerOptions()  
     .position(coordinate)  
     .title("Start")  
     .snippet("Current Location")  
     .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));  
     
     //centering the map to your marker startposition
     map.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 12));  
   }  

   @Override  
   public void onProviderDisabled(String provider) {  
     // TODO Auto-generated method stub     }  

   @Override  
   public void onProviderEnabled(String provider) {  
     // TODO Auto-generated method stub     }  

   @Override  
   public void onStatusChanged(String provider, int status, Bundle extras) {  
     // TODO Auto-generated method stub  
   }  
 }  

and here's the xml


 <fragment xmlns:android="http://schemas.android.com/apk/res/android"  
 android:id="@+id/map"  
 android:layout_width="match_parent"  
 android:layout_height="match_parent"  
 class="com.google.android.gms.maps.SupportMapFragment"/>  

Okay, and don't forget to add some sting to your AndroidManifest.xml


             <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  
           <uses-permission android:name="android.permission.INTERNET" />  
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />  
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />  
        <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />  
       <uses-feature  
            android:glEsVersion="0x00020000"  
            android:required="true"/>  
   <application  
     android:allowBackup="true"  
     android:icon="@drawable/ic_launcher"  
     android:label="@string/app_name"  
     android:theme="@style/AppTheme" >  
      <meta-data  
          android:name="com.google.android.maps.v2.API_KEY"  
          android:value="YOUR_API_KEY" />  


Android and SQLite

Some application requiring a database, for Android we're using SQLite as database. so here I want to sharing about using SQLite database.

Here's the sampe code call DatabaseHandler.java
in this code, I have 2 table call rs_list and rs_admin and database name is rsmanager. DatabaseHandler is use to handle all query.

 package com.ademahendra.database;  
 import java.util.ArrayList;  
 import java.util.List;  
 import android.content.ContentValues;  
 import android.content.Context;  
 import android.database.Cursor;  
 import android.database.sqlite.SQLiteDatabase;  
 import android.database.sqlite.SQLiteOpenHelper;  
 public class DatabaseHandler extends SQLiteOpenHelper {  
   private static final int DATABASE_VERSION = 1;  
   private static final String DATABASE_NAME = "rsmanager";  
      public static final String KEY_ID = "_id";  
      public static final String KEY_NAME = "name";  
      public static final String KEY_EMAIL = "email";  
      public static final String KEY_ADDRESS = "address";  
      public static final String KEY_PHONE = "phone_number";  
      public static final String KEY_IMAGE = "image";  
      public static final String KEY_GLAT = "glat";  
      public static final String KEY_GLON = "glon";  
      public static final String KEY_TYPERS = "typers";  
      public static final String KEY_WEB = "web";  
      public static final String KEY_STATUS = "status";  
      private static final String DB_TABLE = "rs_list";    
      private static final String DB_TABLEADMIN = "rs_admin";  
      public static final String KEY_AID = "id";  
      public static final String KEY_ANAME = "name";  
      public static final String KEY_AUSER = "username";  
      public static final String KEY_APASSWORD = "password";  
   public DatabaseHandler(Context context) {  
     super(context, DATABASE_NAME, null, DATABASE_VERSION);  
   }  
   @Override  
   public void onCreate(SQLiteDatabase db) {  
        db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);  
     String CREATE_CONTACTS_TABLE =   
               "create table rs_list "  
                + "(_id integer primary key autoincrement, "  
                + "name varchar(200) not null,"  
                + "phone_number varchar(200),"  
                + "address varchar(200),"                 
                + "email varchar(200),"        
                + "image varchar(200),"  
                + "glat varchar(15),"  
                + "glon varchar(15),"  
                + "typers varchar(100),"  
                + "web varchar(225),"  
                + "status varchar(11) DEFAULT '0');";  
     db.execSQL(CREATE_CONTACTS_TABLE);  
     db.execSQL("DROP TABLE IF EXISTS " + DB_TABLEADMIN);  
     String CREATE_CONTACTS_TABLEADMIN =   
               "create table rs_admin "  
                + "(_id integer primary key autoincrement, "  
                + "name varchar(200) not null,"  
                + "username varchar(200),"  
                + "password varchar(200));";  
     db.execSQL(CREATE_CONTACTS_TABLEADMIN);  
     db.isOpen();  
   }  
   @Override  
   public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
     db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);  
     db.execSQL("DROP TABLE IF EXISTS " + DB_TABLEADMIN);  
     onCreate(db);  
   }  
      public void addRSList(RSList rslist) {  
     SQLiteDatabase db = this.getWritableDatabase();  
     ContentValues values = new ContentValues();  
     values.put(KEY_NAME, rslist.getName());      
     values.put(KEY_PHONE, rslist.getPhoneNumber());  
     values.put(KEY_EMAIL, rslist.getEmail());  
     values.put(KEY_ADDRESS, rslist.getAddress());  
     values.put(KEY_IMAGE, rslist.getImage());  
     values.put(KEY_GLAT, rslist.getGlat());  
     values.put(KEY_GLON, rslist.getGlon());  
     values.put(KEY_TYPERS, rslist.getTypers());  
     values.put(KEY_WEB, rslist.getWeb());  
     values.put(KEY_STATUS, rslist.getStatus());  
     db.insert(DB_TABLE, null, values);  
     db.close();   
   }  
   public void addRSAmin(Admin admin) {  
     SQLiteDatabase db = this.getWritableDatabase();  
     ContentValues values = new ContentValues();  
     values.put(KEY_ANAME, admin.getName());       
     values.put(KEY_AUSER, admin.getUsername());   
     values.put(KEY_APASSWORD, admin.getPassword());   
     db.insert(DB_TABLEADMIN, null, values);  
     db.close();  
   }  
   RSList getRSList(int id) {  
     SQLiteDatabase db = this.getReadableDatabase();  
     Cursor cursor = db.query(DB_TABLE, new String[] { KEY_ID,  
         KEY_NAME, KEY_PHONE, KEY_EMAIL, KEY_ADDRESS, KEY_IMAGE, KEY_GLAT, KEY_GLON, KEY_TYPERS, KEY_WEB, KEY_STATUS }, KEY_ID + "=?",  
         new String[] { String.valueOf(id) }, null, null, null, null);  
     if (cursor != null)  
       cursor.moveToFirst();  
     RSList rslist = new RSList(Integer.parseInt(cursor.getString(0)),  
         cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5)  
         , cursor.getString(6), cursor.getString(7), cursor.getString(8), cursor.getString(9), cursor.getString(10));  
     return rslist;  
   }  
   Admin getAdmin(int id) {  
     SQLiteDatabase db = this.getReadableDatabase();  
     Cursor cursor = db.query(DB_TABLEADMIN, new String[] { KEY_AID,  
         KEY_ANAME, KEY_AUSER, KEY_APASSWORD}, KEY_AID + "=?",  
         new String[] { String.valueOf(id) }, null, null, null, null);  
     if (cursor != null)  
       cursor.moveToFirst();  
     Admin admin = new Admin(Integer.parseInt(cursor.getString(0)),  
         cursor.getString(1), cursor.getString(2), cursor.getString(3));  
     return admin;  
   }   
   public List<RSList> getAllRSLists() {  
     List<RSList> rslistList = new ArrayList<RSList>();  
     String selectQuery = "SELECT * FROM " + DB_TABLE;  
     SQLiteDatabase db = this.getWritableDatabase();  
     Cursor cursor = db.rawQuery(selectQuery, null);  
     if (cursor.moveToFirst()) {  
       do {  
         RSList rslist = new RSList();  
         rslist.setID(Integer.parseInt(cursor.getString(0)));  
         rslist.setName(cursor.getString(1));  
         rslist.setPhoneNumber(cursor.getString(2));  
         rslist.setEmail(cursor.getString(3));  
         rslist.setAddress(cursor.getString(4));  
         rslist.setImage(cursor.getString(5));  
         rslist.setGlat(cursor.getString(6));  
         rslist.setGlon(cursor.getString(7));  
         rslist.setTypers(cursor.getString(8));  
         rslist.setWeb(cursor.getString(9));  
         rslist.setStatus(cursor.getString(10));  
         rslistList.add(rslist);  
       } while (cursor.moveToNext());  
     }  
     return rslistList;  
   }  
   public List<RSList> getAllRSListsByType(String keyword) {  
     List<RSList> rslistList = new ArrayList<RSList>();  
     String selectQuery = "SELECT * FROM " + DB_TABLE+" WHERE "+KEY_TYPERS+" = '"+keyword+"'";  
     SQLiteDatabase db = this.getWritableDatabase();  
     Cursor cursor = db.rawQuery(selectQuery, null);  
     if (cursor.moveToFirst()) {  
       do {  
         RSList rslist = new RSList();  
         rslist.setID(Integer.parseInt(cursor.getString(0)));  
         rslist.setName(cursor.getString(1));  
         rslist.setPhoneNumber(cursor.getString(2));  
         rslist.setEmail(cursor.getString(3));  
         rslist.setAddress(cursor.getString(4));  
         rslist.setImage(cursor.getString(5));  
         rslist.setGlat(cursor.getString(6));  
         rslist.setGlon(cursor.getString(7));  
         rslist.setTypers(cursor.getString(8));  
         rslist.setWeb(cursor.getString(9));  
         rslist.setStatus(cursor.getString(10));  
         rslistList.add(rslist);  
       } while (cursor.moveToNext());  
     }  
     return rslistList;  
   }    
   public List<RSList> getAllRSListsByName(String keyword) {  
     List<RSList> rslistList = new ArrayList<RSList>();  
     String selectQuery = "SELECT * FROM " + DB_TABLE+" WHERE "+KEY_NAME+" = '"+keyword+"'";  
     SQLiteDatabase db = this.getWritableDatabase();  
     Cursor cursor = db.rawQuery(selectQuery, null);  
     if (cursor.moveToFirst()) {  
       do {  
         RSList rslist = new RSList();  
         rslist.setID(Integer.parseInt(cursor.getString(0)));  
         rslist.setName(cursor.getString(1));  
         rslist.setPhoneNumber(cursor.getString(2));  
         rslist.setEmail(cursor.getString(3));  
         rslist.setAddress(cursor.getString(4));  
         rslist.setImage(cursor.getString(5));  
         rslist.setGlat(cursor.getString(6));  
         rslist.setGlon(cursor.getString(7));  
         rslist.setTypers(cursor.getString(8));  
         rslist.setWeb(cursor.getString(9));  
         rslist.setStatus(cursor.getString(10));  
         rslistList.add(rslist);  
       } while (cursor.moveToNext());  
     }  
     return rslistList;  
   }  
   public List<Admin> getAllAdmin(String keyword) {  
     List<Admin> adminList = new ArrayList<Admin>();  
     String selectQuery = "SELECT * FROM " + DB_TABLEADMIN+" WHERE "+KEY_ANAME+" = '"+keyword+"'";  
     SQLiteDatabase db = this.getWritableDatabase();  
     Cursor cursor = db.rawQuery(selectQuery, null);  
     if (cursor.moveToFirst()) {  
       do {  
         Admin admin = new Admin();  
         admin.setID(Integer.parseInt(cursor.getString(0)));  
         admin.setName(cursor.getString(1));  
         admin.setUsername(cursor.getString(2));  
         admin.setPassword(cursor.getString(3));  
         adminList.add(admin);  
       } while (cursor.moveToNext());  
     }  
     return adminList;  
   }   
   public List<Admin> getAllAdminUser(String keyword) {  
     List<Admin> adminList = new ArrayList<Admin>();  
     String selectQuery = "SELECT * FROM " + DB_TABLEADMIN+" WHERE "+KEY_AUSER+" = '"+keyword+"'";  
     SQLiteDatabase db = this.getWritableDatabase();  
     Cursor cursor = db.rawQuery(selectQuery, null);  
     if (cursor.moveToFirst()) {  
       do {  
         Admin admin = new Admin();  
         admin.setID(Integer.parseInt(cursor.getString(0)));  
         admin.setName(cursor.getString(1));  
         admin.setUsername(cursor.getString(2));  
         admin.setPassword(cursor.getString(3));  
         adminList.add(admin);  
       } while (cursor.moveToNext());  
     }  
     return adminList;  
   }    
   public Cursor getRSListsByType(String keyword) {  
     String selectQuery = "SELECT * FROM " + DB_TABLE+" WHERE "+KEY_TYPERS+" = '"+keyword+"'";  
     SQLiteDatabase db = this.getWritableDatabase();  
     Cursor cursor = db.rawQuery(selectQuery, null);  
     return cursor;  
   }  
   public int updateRSList(RSList rslist) {  
     SQLiteDatabase db = this.getWritableDatabase();  
     ContentValues values = new ContentValues();  
     values.put(KEY_NAME, rslist.getName());  
     values.put(KEY_PHONE, rslist.getPhoneNumber());  
     values.put(KEY_EMAIL, rslist.getEmail());  
     values.put(KEY_ADDRESS, rslist.getAddress());  
     values.put(KEY_IMAGE, rslist.getImage());  
     values.put(KEY_GLAT, rslist.getGlat());  
     values.put(KEY_GLON, rslist.getGlon());  
     values.put(KEY_TYPERS, rslist.getTypers());  
     values.put(KEY_WEB, rslist.getWeb());  
     values.put(KEY_STATUS, rslist.getStatus());  
     return db.update(DB_TABLE, values, KEY_ID + " = ?",  
         new String[] { String.valueOf(rslist.getID()) });  
   }  
   public int updateAdmin(Admin admin) {  
     SQLiteDatabase db = this.getWritableDatabase();  
     ContentValues values = new ContentValues();  
     values.put(KEY_ANAME, admin.getName());  
     values.put(KEY_AUSER, admin.getUsername());  
     values.put(KEY_APASSWORD, admin.getPassword());  
     return db.update(DB_TABLEADMIN, values, KEY_AID + " = ?",  
         new String[] { String.valueOf(admin.getID()) });  
   }    
   public void deleteRSList(RSList rslist) {  
     SQLiteDatabase db = this.getWritableDatabase();  
     db.delete(DB_TABLE, KEY_ID + " = ?",  
         new String[] { String.valueOf(rslist.getID()) });  
     db.close();  
   }  
   public int getRSListsCount() {  
     String countQuery = "SELECT * FROM " + DB_TABLE;  
     SQLiteDatabase db = this.getReadableDatabase();  
     Cursor cursor = db.rawQuery(countQuery, null);  
     cursor.close();  
     return cursor.getCount();  
   }  
   public int getRSListTypeCount(String keyword) {  
     String countQuery = "SELECT * FROM " + DB_TABLE+" WHERE "+KEY_TYPERS+" = '"+keyword+"'";  
     SQLiteDatabase db = this.getReadableDatabase();  
     Cursor cursor = db.rawQuery(countQuery, null);  
     cursor.close();  
     return cursor.getCount();  
   }  
   public int loginAdmin(String username, String password) {  
     String countQuery = "SELECT * FROM " + DB_TABLEADMIN+" WHERE "+KEY_AUSER+" = '"+username+"' AND "+KEY_APASSWORD+  
               "= '"+password+"'";  
     SQLiteDatabase db = this.getReadableDatabase();  
     Cursor cursor = db.rawQuery(countQuery, null);  
     cursor.close();  
     return cursor.getCount();  
   }   
   public List<Admin> getLoginDetail(String username, String password) {  
     List<Admin> adminList = new ArrayList<Admin>();  
     String selectQuery = "SELECT * FROM " + DB_TABLEADMIN+" WHERE "+KEY_AUSER+" = '"+username+"' AND "+KEY_APASSWORD+  
               "= '"+password+"'";  
     SQLiteDatabase db = this.getWritableDatabase();  
     Cursor cursor = db.rawQuery(selectQuery, null);  
     if (cursor.moveToFirst()) {  
       do {  
         Admin admin = new Admin();  
         admin.setID(Integer.parseInt(cursor.getString(0)));  
         admin.setName(cursor.getString(1));  
         admin.setUsername(cursor.getString(2));  
         admin.setPassword(cursor.getString(3));  
         adminList.add(admin);  
       } while (cursor.moveToNext());  
     }  
     return adminList;  
   }    
   public int getExistCount(String keyword) {  
     String countQuery = "SELECT * FROM " + DB_TABLE+" WHERE "+KEY_NAME+" = '"+keyword+"'";  
     SQLiteDatabase db = this.getReadableDatabase();  
     Cursor cursor = db.rawQuery(countQuery, null);  
     cursor.close();  
     return cursor.getCount();  
   }    
 }  

and the second I have file RSList.java. It's a class that used to handle table rs_list. here's the code:

 package com.ademahendra.database;  
 public class RSList {  
   int _id;  
   String _name;  
   String _phone_number;  
   String _email;  
   String _address;  
   String _image;  
   String _glat;  
   String _glon;  
   String _typers;  
   String _web;  
   String _status;  
   public RSList(){  
   }  
   public RSList(int id, String name, String _phone_number, String _email, String _address, String _image, String _glat, String _glon,  
   String _typers, String _web, String _status){  
     this._id = id;  
     this._name = name;  
     this._phone_number = _phone_number;  
     this._email = _email;  
     this._address = _address;  
     this._image = _image;  
     this._glat = _glat;  
     this._glon = _glon;  
     this._typers = _typers;  
     this._web = _web;  
     this._status = _status;  
   }  
   public RSList(String name, String _phone_number, String _email, String _address, String _image, String _glat, String _glon,  
          String _typers, String _web, String _status){  
     this._name = name;  
     this._phone_number = _phone_number;  
     this._email = _email;  
     this._address = _address;  
     this._image = _image;  
     this._glat = _glat;  
     this._glon = _glon;  
     this._typers = _typers;  
     this._web = _web;  
     this._status = _status;  
   }  
   public int getID(){  
     return this._id;  
   }  
   public void setID(int id){  
     this._id = id;  
   }  
   public String getName(){  
     return this._name;  
   }  
   public void setName(String name){  
     this._name = name;  
   }  
   public String getPhoneNumber(){  
     return this._phone_number;  
   }  
   public void setPhoneNumber(String phone_number){  
     this._phone_number = phone_number;  
   }  
   public String getAddress(){  
     return this._address;  
   }  
   public void setAddress(String address){  
     this._address = address;  
   }    
   public String getEmail(){  
     return this._email;  
   }  
   public void setEmail(String email){  
     this._email = email;  
   }   
   public String getImage(){  
     return this._address;  
   }  
   public void setImage(String image){  
     this._image = image;  
   }   
   public String getGlat(){  
     return this._glat;  
   }  
   public void setGlat(String glat){  
     this._glat = glat;  
   }   
   public String getGlon(){  
     return this._glon;  
   }  
   public void setGlon(String glon){  
     this._glon = glon;  
   }  
   public String getTypers(){  
     return this._typers;  
   }  
   public void setTypers(String typers){  
     this._typers = typers;  
   }   
   public String getWeb(){  
     return this._web;  
   }  
   public void setWeb(String web){  
     this._web = web;  
   }   
   public String getStatus(){  
     return this._status;  
   }  
   public void setStatus(String status){  
     this._status = status;  
   }   
 }  

and this is how to call the class for doing some query.


 package com.ademahendra;  
 import com.rumahsakitterdekat.database.DatabaseHandler;  
 import com.rumahsakitterdekat.database.RSList;  
 //...................... and another import ....................................  
 public class MainActivity extends Activity {  
 //...............................................................  
   private DatabaseHandler db;  
 //...............................................................  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);      
     setContentView(R.layout.MainActivity);  
     db = new DatabaseHandler(this);  
     addDB();  
   }  
   public void addDB(){  
        List<RSList> rslist = db.getAllRSListsByName("My Hospita");     
        int total = rslist.toArray().length;  
        if(total < 1){  
             db.addRSList(new RSList("My Hospital", "+62 081 999999999", "The Address", "", "", "-7.982653", "112.628218", "Public Hospital", "", ""));  
        }  
   }  
 }  


Using GPS on Android (Java)

Class for retrieving gps location on android programming.
This source will try to get minimum 4 satellite, if can't get 4 satellite, that's will read last known location. To call this class u can using the code below in your activity:
 public LocationResult locationResult = new LocationResult(){  
     @Override  
     public void gotLocation(final Location location){  
       //Got the location!  
          Glat = location.getLatitude();  
          Glong = location.getLongitude();  
     }  
 }  

To call the function code on top you can using this:
 //declare the class MyLocation first on your activity  
 private MyLocation myLocation = new MyLocation();   
 //call the code location results  
 myLocation.init(this, locationResult);  

Class MyLocation:
 class MyLocation{  
   /**  
    * If GPS is enabled.   
    * Use minimal connected satellites count.  
    */  
   private static final int min_gps_sat_count = 5;  
   /**  
    * Iteration step time.  
    */  
   private static final int iteration_timeout_step = 500;  
   LocationResult locationResult;  
   private Location bestLocation = null;  
   private Handler handler = new Handler();  
   private LocationManager myLocationManager;   
   public Context context;  
   private boolean gps_enabled = false;  
   private int counts  = 0;  
   private int sat_count = 0;  
   private Runnable showTime = new Runnable() {  
      public void run() {  
       boolean stop = false;  
       counts++;  
       //if timeout (1 min) exceeded, stop tying  
       if(counts > 120){  
         stop = true;  
       }  
       //update last best location  
       bestLocation = getLocation(context);  
       //if location is not ready or don`t exists, try again  
       if(bestLocation == null){  
         handler.postDelayed(this, iteration_timeout_step);  
       }else{  
         //if best location is known, calculate if we need to continue to look for better location  
         //if gps is enabled and min satellites count has not been connected or min check count is smaller then 4 (2 sec)   
         if(stop == false && !needToStop()){  
           handler.postDelayed(this, iteration_timeout_step);  
         }else{  
           // removing all updates and listeners  
           myLocationManager.removeUpdates(gpsLocationListener);  
           myLocationManager.removeUpdates(networkLocationListener);    
           myLocationManager.removeGpsStatusListener(gpsStatusListener);  
           sat_count = 0;  
           // send best location to locationResult  
           locationResult.gotLocation(bestLocation);  
         }  
       }  
      }  
   };  
   /**  
    * Determine if continue to try to find best location  
    */  
   private Boolean needToStop(){  
     if(gps_enabled){  
       if(counts <= 4){  
         return false;  
       }  
       if(sat_count < min_gps_sat_count){  
         //if 20-25 sec and 3 satellites found then stop  
         if(counts >= 40 && sat_count >= 3){  
           return true;  
         }  
         return false;  
       }  
     }  
     return true;  
   }  
   //use for stopping retrieving location   
   public void StopLoading(){  
        myLocationManager.removeUpdates(gpsLocationListener);  
     myLocationManager.removeUpdates(networkLocationListener);    
     myLocationManager.removeGpsStatusListener(gpsStatusListener);  
     handler.removeCallbacks(showTime);  
   }  
   /**  
    * Best location abstract result class  
    */  
   public static abstract class LocationResult{  
      public abstract void gotLocation(Location location);  
    }  
   /**  
    * Initialize starting values and starting best location listeners  
    *   
    * @param Context ctx  
    * @param LocationResult result  
    */  
   public void init(Context ctx, LocationResult result){  
     context = ctx;  
     locationResult = result;  
     myLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);  
     gps_enabled = (Boolean) myLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);  
     bestLocation = null;  
     counts = 0;  
     // turning on location updates  
     myLocationManager.requestLocationUpdates("network", 0, 0, networkLocationListener);  
     myLocationManager.requestLocationUpdates("gps", 0, 0, gpsLocationListener);  
     myLocationManager.addGpsStatusListener(gpsStatusListener);  
     // starting best location finder loop  
     handler.postDelayed(showTime, iteration_timeout_step);  
   }  
   /**  
    * GpsStatus listener. OnChainged counts connected satellites count.  
    */  
   public final GpsStatus.Listener gpsStatusListener = new GpsStatus.Listener() {  
     public void onGpsStatusChanged(int event) {  
        if(event == GpsStatus.GPS_EVENT_SATELLITE_STATUS){  
         try {  
           // Check number of satellites in list to determine fix state  
            GpsStatus status = myLocationManager.getGpsStatus(null);  
            Iterable<GpsSatellite>satellites = status.getSatellites();  
            sat_count = 0;  
            Iterator<GpsSatellite>satI = satellites.iterator();  
            while(satI.hasNext()) {  
              GpsSatellite satellite = satI.next();  
              Log.i("GPS Location","Satellite: snr=" + satellite.getSnr() + ", elevation=" + satellite.getElevation());               
              sat_count++;  
            }  
         } catch (Exception e) {  
           e.printStackTrace();  
           sat_count = min_gps_sat_count + 1;  
         }  
        }  
      }  
   };  
   /**  
    * Gps location listener.  
    */  
   public final LocationListener gpsLocationListener = new LocationListener(){  
     public void onLocationChanged(Location location){  
     }  
      public void onProviderDisabled(String provider){}  
      public void onProviderEnabled(String provider){}  
      public void onStatusChanged(String provider, int status, Bundle extras){}  
   };   
   /**  
    * Network location listener.  
    */  
   public final LocationListener networkLocationListener = new LocationListener(){  
     public void onLocationChanged(Location location){  
     }  
      public void onProviderDisabled(String provider){}  
      public void onProviderEnabled(String provider){}  
      public void onStatusChanged(String provider, int status, Bundle extras){}  
   };   
   /**  
    * Returns best location using LocationManager.getBestProvider()  
    *   
    * @param context  
    * @return Location|null  
    */  
   public static Location getLocation(Context context){  
     // fetch last known location and update it  
     try {  
       LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);  
       Criteria criteria = new Criteria();  
       criteria.setAccuracy(Criteria.ACCURACY_FINE);  
        criteria.setAltitudeRequired(false);  
        criteria.setBearingRequired(false);  
        criteria.setCostAllowed(true);  
        String strLocationProvider = lm.getBestProvider(criteria, true);  
        Location location = lm.getLastKnownLocation(strLocationProvider);  
        if(location != null){  
         return location;  
        }  
        return null;  
     } catch (Exception e) {  
       e.printStackTrace();  
       return null;  
     }  
   }  
 }  

Using MapView on Android Application

In this tutorial, I'll try to explain how to use  google map on android application using Google Map API's V1.
First you must get an API Key at http://code.google.com/android/maps-api-signup.html before you debugging your application. You must enter your md5 debug.key, you can search on Google how to get md5 API Key.

first you must add some code to your application manifest. That's code will give your application permission to access google maps.

 //permission to get access for internet and location  
 <uses-permission android:name="android.permission.INTERNET"/>  
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  
 <application>  
 . . . . . . . .  
 <uses-library android:name="com.google.android.maps" />  
 . . . . . . . .   
 </application>  

After you've been add that's code to your application manifest, now you can add to your application layout. Like the code bellow:
           <com.google.android.maps.MapView   
          android:id="@+id/mapView"  
          android:layout_width="290dp"  
          android:layout_height="180dp"           
          android:enabled="true"  
          android:clickable="true"  
          android:layout_gravity="center"  
          android:apiKey="YOUR API KEY PUT HERE" />  

Let's cook the code on your java activity. I'm using GPS to get the location using MyLocation class that's I've been write before. Check my another blog post on Using GPS Satellite.
Declare some variable that's its will be used on mapview.


 public class TodoAddActivity extends MapActivity {  
      MapView mapView;   
      MapController mc;  
   GeoPoint p;  

Code for set MapView. In this code I assume that's you've a Latitude and Longitude value.
      public LocationResult locationResult = new LocationResult(){  
     @Override  
     public void gotLocation(final Location location){  
       //Got the location!  
          Glat = location.getLatitude();  
          Glon = location.getLongitude();  
          mGps.setText(location.getLongitude() + " : " + location.getLatitude());    
          mGps.setEnabled(false);  
          mapView.setVisibility(View.VISIBLE);  
             retrieveLocationButton.setEnabled(true);  
             addnewBtn.setEnabled(true);  
             gpsStatus = true;  
       mapView.invalidate();  
       mc = mapView.getController();  
       p = new GeoPoint(  
         (int) (Glat * 1E6),   
         (int) (Glon * 1E6));  
       mc.animateTo(p);  
       mc.setZoom(17);   
       MapOverlay mapOverlay = new MapOverlay();  
       List<Overlay> listOfOverlays = mapView.getOverlays();  
       listOfOverlays.clear();  
       listOfOverlays.add(mapOverlay);  
       mapView.invalidate();   
       };  
     };  
   class MapOverlay extends com.google.android.maps.Overlay  
   {  
     @Override  
     public boolean draw(Canvas canvas, MapView mapView,   
     boolean shadow, long when)   
     {  
       super.draw(canvas, mapView, shadow);            
       //---translate the GeoPoint to screen pixels---  
       Point screenPts = new Point();  
       mapView.getProjection().toPixels(p, screenPts);  
       //---add the marker---  
       Bitmap bmp = BitmapFactory.decodeResource(  
         getResources(), R.drawable.marker);        
       canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);       
       return true;  
     }  
   }   

There is a Class call MapOverlay. it's use to add marker on your map view. if U don't want an Marker on your map, forget that's class :D. just use that's code, you also can customize your zoom level on mc.setZoom([your value])
     mapView.invalidate();   
     mc = mapView.getController();   
     p = new GeoPoint(   
      (int) (Glat * 1E6),    
      (int) (Glon * 1E6));   
     mc.animateTo(p);   
     mc.setZoom(17);  
Okay. See you in another Android Tutorial.