Getting latitude and longitude in Android - android

I'm trying to learn how to get the current coordinates of an Android device and I have the following code:
package com.example.pruebageolocalizacion;
import java.util.List;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager locManager = (LocationManager)getSystemService(LOCATION_SERVICE);
List<String> listaProviders = locManager.getAllProviders();
for(int i=0;i<listaProviders.size();i++) {
Toast.makeText(getApplicationContext(),listaProviders.get(i).toString(),Toast.LENGTH_LONG).show();
}
if (!locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Toast.makeText(getApplicationContext(), "GPS DESACTIVADO",Toast.LENGTH_LONG).show();
}
else {
Location ultimaLocalizacion = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(ultimaLocalizacion!=null) {
double ultimaLatitud = ultimaLocalizacion.getLatitude();
double ultimaLongitud = ultimaLocalizacion.getLongitude();
Toast.makeText(getApplicationContext(), "Ultma latitud: " + ultimaLatitud ,Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "Ultma longitud: " + ultimaLongitud ,Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "Ultma localizacion es null",Toast.LENGTH_LONG).show();
LocationListener locListener = new LocationListener() {
public void onLocationChanged(Location location) {
Toast.makeText(getApplicationContext(), "Ultma latitud: " + String.valueOf(location.getLatitude()) ,Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "Ultma longitud: " + String.valueOf(location.getLongitude()) ,Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "Precision: " + String.valueOf(location.getAccuracy()) ,Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String provider){
Toast.makeText(getApplicationContext(), "GPS DESACTIVADO",Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String provider){
Toast.makeText(getApplicationContext(), "GPS ACTIVADO",Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String provider, int status, Bundle extras){
Toast.makeText(getApplicationContext(), "Status del proveedor" + status,Toast.LENGTH_LONG).show();
}
};
Toast.makeText(getApplicationContext(), "A",Toast.LENGTH_LONG).show();
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, locListener);
Toast.makeText(getApplicationContext(), "B",Toast.LENGTH_LONG).show();
}
}
}
}
I have tried it both in an Android virtual device and in my cell phone and these are the messages I can see on the screen:
"network", "passive", "gps", "Ultma localizacion es null", "A", "B",
I have enabled WIFI and GPS in both devices. And I have used the GPS of my cell phone many times. So, shouldn't ultimaLocalizacion be different from null?
Also, if ultimaLocalizacion is null, why doesn't it show me the latitude, longitude and accuracy every three seconds?
Thanks a lot.

Related

GetApplicationConext() error

So today I started reading on tutorials on how to get my current GPS location using Android studio. but I came up with an error " Error:(21, 24) error: cannot find symbol method getApplicationContext() " I have looked around stuckoverflow but none of the solutions worked for me. here is the code
package com.example.chara.usegps;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.widget.Toast;
/**
* Created by charalambous on 11/9/2015.
*/
public class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
location.getLatitude();
location.getLongitude();
String Text = "My Current Location is: " + " Latitude = " + location.getLatitude() + "longitude = " + location.getLongitude();
Toast.makeText(getApplicationContext(),Text,Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT).show();
}
}
This is because your class is not extended from ActivityClass. you must add a Context object to your Costructor method and use it as context.

Getting longitude and latitude works in emulator but not on device?

I've been trying to work GPS coordinates but it's been a lot tougher than I thought. After a few hours of trial and error, I've managed to output the latitude and longitude (mocked) for my emulator. Below are the 2 ways I've done it:
First way:
import java.io.IOException;
import java.util.Calendar;
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.util.Log;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String text = "";
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null) {
showMyAddress(location);
}
final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
showMyAddress(location);
}
public void onProviderDisabled(String arg0) {
}
public void onProviderEnabled(String arg0) {
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
};
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 10, locationListener);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Log.i(TAG, "longitude: " + longitude);
Log.i(TAG, "latitude: " + latitude);
text = "longitude: " + longitude + ", " + "latitude: " + latitude;
TextView textView = (TextView) findViewById(R.id.txtvwMain);
textView.setText(text);
}
private void showMyAddress(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder myLocation = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> myList;
try {
myList = myLocation.getFromLocation(latitude, longitude, 1);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
Second way:
import android.app.Activity;
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;
public class MainActivity extends Activity implements LocationListener
{
private LocationManager lm;
private TextView tv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.txtvwMain);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 1, this);
Location location = lm.getLastKnownLocation(lm.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
tv.setText("latitude="+latitude+", longitude="+longitude);
}
#Override
public void onLocationChanged(Location arg0) {
String lat = String.valueOf(arg0.getLatitude());
String lon = String.valueOf(arg0.getLongitude());
Log.e("GPS", "location changed: lat="+lat+", lon="+lon);
tv.setText("lat="+lat+", lon="+lon);
}
public void onProviderDisabled(String arg0) {
Log.e("GPS", "provider disabled " + arg0);
}
public void onProviderEnabled(String arg0) {
Log.e("GPS", "provider enabled " + arg0);
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
Log.e("GPS", "status changed to " + arg0 + " [" + arg1 + "]");
}
}
Both ways above work and print out the mock latitude and longitude onto a TextView in the emulator (running Android 4.2.2). However, when I upload the .apk file onto my device (tablet running Android 4.0.4), it just crashes. I don't know what's wrong because I can't see any error messages. What is the source of the problem and how may I go about solving it? Thanks.

how to get postal code using reverse geocoding in android

I am new to Andriod development..i try to get postal code and city name from reverse geocoding using below code.it finding latitude, longitude value fine but cant able to get cityname and postal code.
package com.example.code;
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.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class LbsGeocodingActivity extends Activity {
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
protected LocationManager locationManager;
protected Button retrieveLocationButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
retrieveLocationButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showCurrentLocation();
}
});
}
protected void showCurrentLocation() {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Geocoder gcoder=new Geocoder(this, Locale.ENGLISH);
List<Address> Data = null;
double latitude;
double longitude;
if (location != null) {
latitude=location.getLatitude();
longitude=location.getLongitude();
try {
Data=gcoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String cityname=Data.get(0).getLocality();
String postalcode=Data.get(0).getPostalCode();
String message=String.format("City Name \n PostalCode \n", Data.get(0).getLocality(),Data.get(0).getPostalCode());
Toast.makeText(LbsGeocodingActivity.this,message ,
Toast.LENGTH_LONG).show();
}
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(LbsGeocodingActivity.this, message, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(LbsGeocodingActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(LbsGeocodingActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(LbsGeocodingActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show(); }
}
}
It looks like your code for finding the city and zipcode is right, but your code for formatting the string for your toast is wrong. It does not put the values in there.
It should look like this:
String message=String.format("City Name %s \n PostalCode %d \n", Data.get(0).getLocality(),Data.get(0).getPostalCode());
The %s represents a string and the %s represents a decimal number (integer).

Why does Location.getAltitude() always return zero, at least in the emulator?

Does anybody know why my getAltitude in the following always returns 0?
package com.example.helloandroid;
import android.app.Activity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
public class HelloAndroid extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
Log.d("main", "onCreate");
setupGps();
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
LocationListener locationListener;
LocationManager lm;
void setupGps() {
Log.d("gps", "Setting up GPS...");
locationListener = new MyLocationListener();
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 20000, 5,
locationListener);
Log.d("gps",
"GPS supports altitude: "
+ lm.getProvider(LocationManager.GPS_PROVIDER)
.supportsAltitude());
Log.d("gps", "Finished setting up GPS.");
}
static class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
Log.d("gps", "onLocationChanged");
Log.d("gps",
"x: " + location.getLongitude() + ", y: "
+ location.getLatitude() + ", alt.: "
+ location.getAltitude());
}
public void onProviderDisabled(String provider) {
Log.d("gps", "onProviderDisabled");
}
public void onProviderEnabled(String provider) {
Log.d("gps", "onProviderEnabled");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("gps",
"onStatusChanged; new status: " + String.valueOf(status));
}
}
}
To test, I issue a geo command with an altitude to the emulator:
[someone#somewhere ~]$ telnet localhost 5554
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Android Console: type 'help' for a list of commands
OK
geo fix -121.45356 46.51119 4392
OK
But getAltitude() returns 0:
I have only tried with emulated devices.
Edit
Following up on cheeken's comment, I verified that Location.hasAltitude() is true. It is. Any other idea?
public void onLocationChanged(Location location) {
Log.d("gps", "onLocationChanged");
Log.d("gps", "x: " + location.getLongitude()
+ ", y: " + location.getLatitude());
Log.d("gps", "hasAltitude: " + location.hasAltitude()
+ ", alt.: " + location.getAltitude());
}
It seems like a lot of people are having similar issues with this and has even been reported as a possible bug. I wouldn't be surprised if the emulator simply doesn't support it at this time. You'll probably have to work with a real device.

Finding current Location when the application is running in background is not working

I want to find out current location when the Application is running in background
I Have below code for finding current location in background running services. But its not working.
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
public class MyService extends Service {
private static LocationManager mlocManager;
private static final String TAG = "MyService";
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
}
#Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "start My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
//Location newloc= new Location();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
Toast.makeText(this, "hiiiits created", Toast.LENGTH_LONG).show();
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
Log.d(TAG, "onlocationchnage");
loc.getLatitude();
loc.getLongitude();
String Text ="My current location is: " +
"Latitud = " + loc.getLatitude() +
"Longitud = " + loc.getLongitude();
Toast.makeText( getApplicationContext(),
Text,
Toast.LENGTH_SHORT).show();
}
#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)
{
}
}/* End of Class MyLocationListener */
}
I think you need Current Latitude and Longitude values using GPS..
follow this link.. Click link
I already tried it and test it in android mobile phone.. Its working.
Note :
emulator we are not get the Curent GPS location.. You must and should install your application in phone..
First you ON the GPS in mobile phone after try it, it will work.
have a nice day.

Categories

Resources