I am trying to find my current location for an android project. When the application is loaded my current location is always null. I have set up the permissions in the manifest etc. When I find the current location I intend to use the coordinates to find distances to other locations on the map. My code snippet is below. Why do i always get a null value?
Here is my code:-
package com.example.location;
import android.content.Context;
import android.location.LocationManager;
import android.os.Bundle;
import android.location.Location;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import android.location.LocationListener;
import com.google.android.maps.MapController;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
public class MainActivity extends MapActivity implements LocationListener {
private MapView mapView;
private LocationManager locManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//fetch the map view from the layout
MapView mapView = (MapView) findViewById(R.id.mapview);
//make available zoom controls
mapView.setBuiltInZoomControls(true);
//latitude and longitude of Rome
double lat = 33.6667;
double lon = 73.1667;
//create geo point
GeoPoint point = new GeoPoint((int)(lat * 1E6), (int)(lon *1E6));
//get the MapController object
MapController controller = mapView.getController();
//animate to the desired point
controller.animateTo(point);
//set the map zoom to 13
// zoom 1 is top world view
controller.setZoom(13);
// invalidate the map in order to show changes
**mapView.invalidate();
// Use the location manager through GPS
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
0, this);
//get the current location (last known location) from the location manager
Location location = locManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
Toast.makeText(
this,
"Current location:\nLatitude: " + location.getLatitude()
+ "\n" + "Longitude: " + location.getLongitude(),
Toast.LENGTH_LONG).show(); }
else {
Toast.makeText(this, "Cannot fetch current location!",
Toast.LENGTH_LONG).show();
}**
//when the current location is found – stop listening for updates (preserves battery)
locManager.removeUpdates(this);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
#Override
protected void onPause() {
super.onPause();
locManager.removeUpdates(this); //activity pauses => stop listening for updates
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
Look at this example. very good example for doing things like you want.
http://mobile.tutsplus.com/tutorials/android/android-sdk-build-a-mall-finder-app-points-of-interest/
Related
I am Trying to develop small application in which i am trying to Detect Location.
I am using the following code but i don't know why my application crashes. It show the application stops Unfortunately.
Here is the code. Please tell me if there is any bug and if not then please at least reply.
Thanks.
Here is the Code.
package com.project.kamani.nearby;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class Map extends Activity implements LocationListener{
public GoogleMap google_map;
public List<Address> addresses;
public Geocoder geocoder;
private Location location;
private double lat;
private double lang;
private Criteria criteria;
private LocationManager location_manager;
private String provider;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES=20;//DISTANCE IN METERS
private static final long MIN_TIME_BW_UPDATES=1000*60*1;// TAKES UPDATE AFTER 1 MINUTES
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(isGooglePlayAvailable())
{
criteria=new Criteria();
setContentView(R.layout.mapdemo);
getGoogleMap();
getUserLocation();
//Toast.makeText(this, "Latitude:"+lat+" Longitude:"+lang, Toast.LENGTH_LONG).show();
getAddress(lat,lang);
drawMarker(lat,lang);
}
}
private boolean isGooglePlayAvailable(){
int status=GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(status==ConnectionResult.SUCCESS)
return true;
else
GooglePlayServicesUtil.getErrorDialog(status, this, 10).show();
return false;
}
private void getGoogleMap(){
if(google_map==null){
google_map=((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
}
}
private void drawMarker(double lattitude,double longitude){
google_map.clear();
google_map.setMyLocationEnabled(true);
LatLng latlng=new LatLng(lattitude, longitude);
google_map.moveCamera(CameraUpdateFactory.newLatLng(latlng));
google_map.animateCamera(CameraUpdateFactory.zoomTo(15));
LatLng currentPosition = new LatLng(lattitude,longitude);
google_map.addMarker(new MarkerOptions().position(currentPosition).snippet("Address:" + addresses.get(0).getAddressLine(0) + "City:"+ addresses.get(0).getAddressLine(1)+"Country:"+addresses.get(0).getAddressLine(2)).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)).title("ME"));
}
private void getAddress(double lattitude,double longitude){
geocoder=new Geocoder(Map.this, Locale.getDefault());
try {
addresses=geocoder.getFromLocation(lattitude, longitude, 1);
Toast.makeText(Map.this, "Address:" + addresses.get(0).getAddressLine(0) + "City:"+ addresses.get(0).getAddressLine(1)+"Country:"+addresses.get(0).getAddressLine(2), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
private void getUserLocation(){
location_manager=(LocationManager) getSystemService(LOCATION_SERVICE);
if(location_manager!=null){
provider=location_manager.getBestProvider(criteria, true);
location=location_manager.getLastKnownLocation(provider);
location_manager.requestLocationUpdates(provider, Map.MIN_TIME_BW_UPDATES, Map.MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
lat=location.getLatitude();
lang=location.getLongitude();
}
}
#Override
public void onLocationChanged(Location location) {
google_map.clear();
drawMarker(lat, lang);
}
#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
}
}
Here is the snapshot that error i am getting in logcat.
I hope it will be helpful to solve error.
EDIT:-
If you don't want to monitor once again full code just try to view at getUserLocation method still the application stops working when i enable the GPS thanks for your support.
location is never initialized. Your are setting location as the variable that will hold the return value of getUserLocation() and it is also its parameter; both are null.
public class MainActivity extends MapActivity implements LocationListener {
private MapView mapView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting reference to MapView
mapView = (MapView) findViewById(R.id.map_view);
// Setting Zoom Controls on MapView
mapView.setBuiltInZoomControls(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
#Override
public void onLocationChanged(Location location) {
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// Getting latitude
double latitude = location.getLatitude();
// Getting longitude
double longitude = location.getLongitude();
// Setting latitude and longitude in the TextView tv_location
tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude );
// Creating an instance of GeoPoint corresponding to latitude and longitude
GeoPoint point = new GeoPoint((int)(latitude * 1E6), (int)(longitude*1E6));
// Getting MapController
MapController mapController = mapView.getController();
// Locating the Geographical point in the Map
mapController.animateTo(point);
// Applying a zoom
mapController.setZoom(15);
// Redraw the map
mapView.invalidate();
// Getting list of overlays available in the map
List<Overlay> mapOverlays = mapView.getOverlays();
// Creating a drawable object to represent the image of mark in the map
Drawable drawable = this.getResources().getDrawable(R.drawable.cur_position);
// Creating an instance of ItemizedOverlay to mark the current location in the map
CurrentLocationOverlay currentLocationOverlay = new CurrentLocationOverlay(drawable);
// Creating an item to represent a mark in the overlay
OverlayItem currentLocation = new OverlayItem(point, "Current Location", "Latitude : " + latitude + ", Longitude:" + longitude);
// Adding the mark to the overlay
currentLocationOverlay.addOverlay(currentLocation);
// Clear Existing overlays in the map
mapOverlays.clear();
// Adding new overlay to map overlay
mapOverlays.add(currentLocationOverlay);
}
#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
}
}
Download Here
I have an app with google maps with one single activity where a map is displayed. I have a menu that allows me to change the map type from but I would like to have an option to get my current location.
Here's the code of my activity:
package com.example.chiapa_mapas;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdateFactory;
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.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.MenuInflater;
import android.view.MenuItem;
public class MainActivity extends android.support.v4.app.FragmentActivity implements OnMapClickListener, LocationListener{
private GoogleMap mMap;
private Context ctx;
private LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
mMap.setOnMapClickListener(this);
// Enable LocationLayer of Google Map
mMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
}
#Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.layout.opcoes, menu);
return true; }
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.normal:
mMap.setMapType(1);
break;
case R.id.satellite:
mMap.setMapType(2);
break;
case R.id.terrain:
mMap.setMapType(3);
break;
case R.id.hybrid:
mMap.setMapType(4);
break;
case R.id.none:
mMap.setMapType(0);
break;
case R.id.posicao_actual:
//mMap.setMapType(0);
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria,true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0,(android.location.LocationListener) ctx);
break;
default: return super.onOptionsItemSelected(item);
}
return true;
}
#Override
public void onMapClick(LatLng position) {
// TODO Auto-generated method stub
mMap.addMarker(new MarkerOptions().position(position).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
//double ltt = position.latitude;
//double lgt = position.longitude;
//String msg = "Latitude: " + Double.toString(ltt) + " , Longitude: " + Double.toString(lgt) + "";
//Toast toast = Toast.makeText(ctx, msg, Toast.LENGTH_SHORT);
//toast.show();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
// Setting latitude and longitude in the TextView
locationManager.removeUpdates((android.location.LocationListener) this);
}
}
Can someone help? When I press the option "posicao actual" (current location) it crashes.
Thanks in advance
Chiapa
This works for me:
public void methodName(){
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
android.location.LocationListener locationListener = new android.location.LocationListener() {
public void onLocationChanged(Location location) {
//Any method here
}
public void onStatusChanged (String provider, int status, Bundle extras){}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled (String provider){}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0, locationListener);
}
Thanks chiapa.
change
locationManager.requestLocationUpdates(provider, 20000, 0,(android.location.LocationListener) ctx);
to
locationManager.requestLocationUpdates(provider, 20000, 0,this);
and remove updates too
I am trying to get a location (latitude, longitude) on my Android smartphone (HTC Desire HD), using Wifi-network and GPS.
This is the code I use, only I keep getting "Location not available"
Iam working with Eclipse IDE.
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import com.example.shortsproject.R;
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 LocationGetter extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
latituteField = (TextView) findViewById(R.id.locationtext);
longitudeField = (TextView) findViewById(R.id.locationtext2);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the location provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
Can someone help me with this?
I need a simple android app which can be installed on any android supporting device; I need this app to send the coordinates of its current location every 5 minutes so that it can be sent to sql database
Thanks
This is the code from which i am showing my current location and getting the co-ordinates values(as toast message for now)
Now i need to send this location co-ordinate to the database after every 5 minutes
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.iconnectgroup.LocateDeviceApp.Gps.MyPositionOverlay;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class HelloGoogleMaps extends MapActivity {
MapController mapController;
MyLocationOverlay myLocationOverlay ;
MyPositionOverlay positionOverlay;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapController = mapView.getController();
mapController.setZoom(17);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
mapView.setStreetView(true);
myLocationOverlay = new MyLocationOverlay(this, mapView);
mapView.getOverlays().add(myLocationOverlay);
myLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
mapView.getController().animateTo(
myLocationOverlay.getMyLocation());
}
});
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = "Truck location is: " +
"Latitude = " + loc.getLatitude() +
"Longitude = " + loc.getLongitude();
Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_LONG).show();
Log.e("co-ordinates are:", Text);
}
#Override
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_LONG ).show();
}
#Override
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
#Override
protected void onResume() {
super.onResume();
myLocationOverlay.enableCompass();
myLocationOverlay.enableMyLocation();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
myLocationOverlay.disableCompass();
myLocationOverlay.disableMyLocation();
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
here i make one program in this i set the time in requestlocationsupdates method is 61000 miliseconds .so from emulator in DDMS i change the location lati and longi but dnt press send button. now after 61 seconds why not update new inserted lat long in my emulator automatically after 61 seconds.
here is my code...
package com.getlocation;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
public class ShowMap extends MapActivity
{
TextView tv;
/*private MapController mapController;
private MapView mapView;*/
private LocationManager locationManager;
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.main); // bind the layout to the activity
tv=(TextView) findViewById(R.id.textView1);
// create a map view
//RelativeLayout linearLayout = (RelativeLayout) findViewById(R.id.mainlayout);
//mapView = (MapView) findViewById(R.id.mapview);
//mapView.setBuiltInZoomControls(true);
//mapView.setStreetView(true);
//mapController = mapView.getController();
//mapController.setZoom(14); // Zoon 1 is world view
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 61000,
10, new GeoUpdateHandler());
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
public class GeoUpdateHandler implements LocationListener {
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude() * 1E6);
int lng = (int) (location.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(lat, lng);
//mapController.animateTo(point); //
//mapController.setCenter(point);
tv.setText(String.valueOf(lat));
tv.append("\n"+String.valueOf(lng));
Log.d("Tag", "Starting update");
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
#saurabh
Emulator can not detect location automatically but it detect location if we provide latitude and longitude and press on send button
You are provide initial latitude and longitude in requestLocationUpdate and also setting minimum time and distance so it will work but it can not understand new location without providing latitude and longitude and press send button
so best testing is on device
best of luck