i was made an finding location application that show a latitude and longitude in the textview.. here's my code :
package com.application.geocoding;
import android.app.Activity;
import android.os.Bundle;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.widget.TextView;
public class main extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
String provider = LocationManager.GPS_PROVIDER;
Location location =
locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
}
private void updateWithNewLocation(Location location) {
String latLongString;
TextView myLocationText;
myLocationText=(TextView)findViewById(R.id.textView1);
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "\nLong:" + lng;
} else {
latLongString = "No location found";
}
myLocationText.setText("Your Current Position is:\n" +
latLongString);
}
}
and here's the manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.application.geocoding"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".main"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
that code is still not works and only can display "No location found" textview.. has anyone know how to solve that problem?? thanks..
You can use this:
LocationListener myLocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
String latLongString;
TextView myLocationText;
myLocationText=(TextView)findViewById(R.id.textView1);
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "\nLong:" + lng;
myLocationText.setText("Your Current Position is:\n" +
latLongString);
}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
};
int t = 5000; // millisekunder
int dist = 5; // meter
locationManager.requestLocationUpdates(provider, t, dist, myLocationListener);
from your activity start it will get the gps coordinate but at that time if you don't send the gps coordinate from the ddms then it will return null
while this will give you just one time value if you want to getting the continue gps value you need to define listener for that like LocationListener
see the tutorial link
http://developer.android.com/guide/topics/location/obtaining-user-location.html
http://www.firstdroid.com/2010/04/29/android-development-using-gps-to-get-current-location-2/
http://www.androidcompetencycenter.com/?s=GPS
Have you tried implementing LocationListener and overriding onLocationChanged(Location loc) ? Also, are you using the emulator? EDIT: You can find an example here.
You're not actually invoking a GPS location acquisition, but asking for the last one. If it's never been invoked, it will always return null.
A better approach would be registering a LocationListener in onResume() and unregistering it in onPause() through locationManager.requestLocattionUpdates() and locationManager.removeUpdates(), respectfully.
Related
I only want to get current location updates when I move atleast 3 meters from current location for this I used
FusedLocationClient.requestLocationUpdates
for this i made LocationRequest like this:
private LocationRequest requestLocation(){
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setSmallestDisplacement(3.81f);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
return mLocationRequest;
}
and implemented like this: after connected to play service
#Override
public void onConnected(Bundle bundle) {
mFusedLocationClient.requestLocationUpdates(requestLocation(),
new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
for (final Location location : locationResult.getLocations()) {
tvLat.setText(Double.toString(location.getLatitude()));
tvLng.setText(Double.toString(location.getLongitude()));
//changing position of marker and camera
changeCameraPosition(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()),
16), new GoogleMap.CancelableCallback() {
#Override
public void onFinish() {}
#Override
public void onCancel() { }
});
}
}
}, Looper.myLooper());
but Im getting latlng from this atleast 650m far from my current location even if I didn't move slightest, here is my permissions in manifest:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="permission.READ_GSERVICES" />
Maybe you could check this one : Android map Update location to server when there is difference of x meters between current location and last location and see the difference of your distance when you moved, so you will know where the source of the over-movement occured.
I have application in Android Studio, that shows Google Map using Google Play Services. Application is written for Android 4.0.3. I have generated API key for Google Maps and placed it in google_maps_api.xml file according to this tutorial. Also I added entry for Google API key and permissions for GPS (to use location), Google Services and network in Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="vkalashnykov.org.mapygoogle">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Also I added code for activity:
package vkalashnykov.org.mapygoogle;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
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 MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
private static final int LOCATION_MIN_TIME = 30 * 10;
private static final int LOCATION_MIN_DISTANCE = 1;
private LocationManager locationManager;
private Location currentLocation;
public static final String FIXED = "FIXED";
double szerokosc_g; // latitude
double dlugosc_g; // longitude
static final Integer LOCATION = 0x1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
if (Build.VERSION.SDK_INT >= 23) {
if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(MapsActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION);
} else {
//Metoda requestPermissions jest wywoływana aby uzytkownik mógł podjąć decyzję o nadaniu uprawnien
ActivityCompat.requestPermissions(MapsActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION);
}
} else {
Toast.makeText(MapsActivity.this, " " + Manifest.permission.ACCESS_FINE_LOCATION + " uprawnienia zostały przyznane.", Toast.LENGTH_SHORT).show();
}
if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MapsActivity.this, " " + Manifest.permission.ACCESS_FINE_LOCATION + "Uprawnienia nie zostały nadane", Toast.LENGTH_SHORT).show();
}
Toast.makeText(MapsActivity.this, "Wersja SDK systemu Android : " + Build.VERSION.SDK_INT , Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MapsActivity.this, "Wersja SDK systemu Android : " + Build.VERSION.SDK_INT , Toast.LENGTH_SHORT).show();
}
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{ return; }
szerokosc_g = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLatitude();
dlugosc_g = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLongitude();
LatLng pozycja = new LatLng(szerokosc_g,dlugosc_g); //adding position
mMap.addMarker(new MarkerOptions().position(pozycja).title("Pozycja"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(pozycja));
}
#Override
protected void onStart() {
super.onStart();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if ( ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions( this, new String[] { android.Manifest.permission.ACCESS_COARSE_LOCATION },
LOCATION );
}
else
{ locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_MIN_TIME, LOCATION_MIN_DISTANCE, this);
Location gpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (gpsLocation != null) {
currentLocation = gpsLocation;
} else {
Location networkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (networkLocation != null) {
currentLocation = networkLocation;
} else {
currentLocation = new Location(FIXED);
currentLocation.setAltitude(1);
currentLocation.setLatitude(43.296482);
currentLocation.setLongitude(5.36978);
}
onLocationChanged(currentLocation);
}
}
}
#Override
public void onLocationChanged(Location location) {
szerokosc_g = location.getLatitude();
dlugosc_g = location.getLongitude();
LatLng pozycja = new LatLng(szerokosc_g, dlugosc_g);
mMap.clear();
mMap.addMarker(new MarkerOptions().position(pozycja).title("Pozycja"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(pozycja));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
But all I get when run application is unexpected error: "Unfortunally application stopped." What is wrong or how I can check what is wrong with appplcation (on Android Studio there is no any message or logs about error)?
So I have an app written in Android Eclipse that displays a map over a fixed marker and then moves around based on the change in rotation using a rotation vector sensor. When I ran it on my device, the screen would not move when the phone was tilted. I tried everything and even had my professor look at it. He could not find the problem in the code. Finally we ran it on his device and it worked perfectly! I have a Moto G and I was wondering if anyone new why this code works on other android devices but not mine. Below is the code for the project.
package com.example.flymap_awc;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.Menu;
import android.util.Log;
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.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends Activity implements SensorEventListener {
static final LatLng HAMBURG = new LatLng(53.558, 9.927);
static final LatLng KIEL = new LatLng(53.551, 9.993);
private GoogleMap map;
private SensorManager mSensorManager;
private double oldx = 0, oldy=0, oldz = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
Marker hamburg = map.addMarker(new MarkerOptions().position(HAMBURG)
.title("Hamburg"));
Marker kiel = map.addMarker(new MarkerOptions()
.position(KIEL)
.title("Kiel")
.snippet("Kiel is cool")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_launcher)));
// Move the camera instantly to hamburg with a zoom of 15.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG, 15));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR)
{
if(oldx==0 && oldy ==0 && oldz ==0 ){
// if this is the first run (oldx/y/z=0, get the initial orientation
oldx = event.values[0];
oldy = event.values[1];
oldz =event.values[2];
//set oldx to event.values[0], etc.
}
// get change in rotation amount store as dx,dy,dz
double dx = oldx - event.values[0];
double dy = oldy - event.values[1];
double dz = oldz - event.values[2];
double dTotal = Math.abs(dx) + Math.abs(dy) + Math.abs(dz);
if (dTotal > 0.05)
{
double lat = map.getCameraPosition().target.latitude;
double lng = map.getCameraPosition().target.longitude;
lat +=dx;
lng -=dy;
Log.println(100,"100","lat, lng, dx, dy" + lat + lng+dx+dy);
LatLng loc = new LatLng(lat, lng);
map.moveCamera(CameraUpdateFactory.newLatLng(loc));
oldx = event.values[0];
oldy = event.values[1];
oldz = event.values[2];
}
//filter out noise where Math.abs(dx) + Math.abs(dy)+ Math.abs(dz) > 0.05
// get current lat lng
//that my map camera is point at (or targeting)
// add to the lat and lng based on dx dy
//may want to compensate for zoom inverse proportionally
//may have to do lng -=dy to move intuitively
//move camera using camerupdatefactory to the new LatLng(lat,lng)
// update old oldy oldz
}
}
protected void onResume(){
super.onResume();
// register this class as a listener for the orientation sensor
mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR),
SensorManager.SENSOR_DELAY_NORMAL);
}
protected void onPause(){
super.onPause();
//unregister listener
mSensorManager.unregisterListener(this);
}
}
And here is the manifest code
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.flymap_awc"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="19"
android:targetSdkVersion="19" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<!-- The following two permissions are not required to use
Google Maps Android API v2, but are recommended. -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<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.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name="com.example.flymap_awc.MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyDC4pK6_RmiSsDoWFAEmTUO2DRynTR0lik"/>
</application>
</manifest>
ROTATION_VECTOR requires gyroscope to work, that's why.
Underlying base sensor(s): Accelerometer, Gyroscope AND Magnetometer
One of my app stopped working too due to that, on the Moto G.
I just had a quick glance over your code. I think the problem is that your code is assuming that the sensor is present and successfully registered. In my limited experience, the sensor may be unavailable due to either not existing in the device or being faulty.
Try doing the following checks and see what you get:
Ensure mSensorManager.registerListener returns true.
Ensure mSensorManager.getDefaultSensor doesn't return null.
Ensure onSensorChanged gets called. You could put a breakpoint in it or add a line to write a log message.
I'm new to Android programming and wanted to start by creating a very basic app that displays the latitude and longitude of the current location on screen.
I'm developing for my Samsung Galaxy S3 and read that you need to kickstart the phone to return the GPS.
I've tried doing this in the onConnected() method with the requestLocationUpdates() method call on the LocationManager. However I find that the LocationClient is still returning a null location.
Can anyone tell me what I'm doing wrong?
Here's my MainActivity:
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
public class MainActivity extends FragmentActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
private LocationClient mLocationClient;
private Location mCurrentLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLocationClient = new LocationClient(this, this, this);
}
#Override
protected void onStart() {
super.onStart();
mLocationClient.connect();
}
#Override
protected void onStop() {
mLocationClient.disconnect();
super.onStop();
}
#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 void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
LocationManager manager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
new LocationListener() {
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onLocationChanged(final Location location) {
}
});
mCurrentLocation = mLocationClient.getLastLocation();
TextView latTextView = (TextView) findViewById(R.id.latitude_text);
latTextView.setText(Double.toString(mCurrentLocation.getLatitude()));
TextView longTextView = (TextView) findViewById(R.id.longitude_text);
longTextView.setText(Double.toString(mCurrentLocation.getLongitude()));
}
#Override
public void onDisconnected() {
Toast.makeText(this, "Disconnected. Please re-connect.",
Toast.LENGTH_SHORT).show();
}
}
My Android manifest looks like this:
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.willigetwet.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
When running the debugger I find that mCurrentLocation is null after the call to mLocationClient.getLastLocation().
I'd be very grateful for any help!
mLocationClient.getLastLocation(); might return null if you don't have any last location saved by the device. If you read its documentation, it says;
It returns the best most recent location currently available.
If a location is not available, which should happen very rarely, null will be returned
Also inside the onLocationChanged method you might want to set the Location to the latest location, when your location gets changed.
#Override
public void onLocationChanged(final Location location) {
mCurrentLocation = location;
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Android AVD wifi error
I am working with Android, and I want to show current latitude value in textbox and current longitude value in another textbox. And I wrote the below code, but it is not working. It is not setting any latitude or longitude value in the corresponding textbox. Is there any problem with my code?
public class MainActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
private static final String TAG = "CurrentLocation";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latituteField = (TextView) findViewById(R.id.lat1);
longitudeField = (TextView) findViewById(R.id.lat2);
// 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);
locationManager.requestLocationUpdates(provider, 0, 0, this);
Location location = locationManager.getLastKnownLocation(provider);
onLocationChanged(location);
}
#Override
protected void onDestroy() {
super.onDestroy();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
Log.e("GPS", "location changed: lat="+lat+", lon="+lng);
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
} else {
latituteField.setText("Provider not available");
longitudeField.setText("Provider not available");
}
}
#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
}
}
Or I need to do something such as passing latitude or longitude value from somwhere? Or it will automatically get the current location value?
I have these in my manifest file-
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES" />
<uses-permission android:name="android.permission.INTERNET" />
Anything else I need to add?
And also I am getting this error when I saw in logCAT
07-18 22:43:59.836: E/Trace(3410): error opening trace file: No such file or directory (2)
I am getting in my textbox as Provider Not Available as it is going to else loop.
As you mentioned in the comment that you are running your code from eclipse. Let me tell you that, can not fetch the real GPS Co-Ordinates in Eclipse. However you can simulate it by load .gpx file in to DDMS.
Have a visit my answer for same purpose.
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
you should have double instead of int, Do you know lat, longs are in double and you are only taking integer part. location changes even after 4 decimal places.