Show Latitude and Longitude as soon as LocationManger gets it - android

I am developing a Emergency SMS that whenever you access the activity, the GPS will be enabled and the Location of the user will be shown in a textview, then whenever the user presses send it will be sent to the targeted device. now if i am using Network_Provider the Textview will get the Latitude and Longitude as fast as i access my activity and the message will be showin the textview. however, GPS will show an empty textview and empty Location.
Here is my Code:
public class SMSmyLocation extends Activity implements OnClickListener, LocationListener{
LocationManager locationManager;
LocationListener locationListner;
Context ctx = SMSmyLocation.this;
TextView tv1, tv2;
Button b1;
EditText ed;
Geocoder geo;
List<Address> addresses;
String address = "";
boolean visibility = false;
double Long = 0,Lad = 0;
SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_smsmy_location);
tv1 = (TextView) findViewById(R.id.ESMS);
tv2 = (TextView) findViewById(R.id.currentLocation);
b1 = (Button) findViewById(R.id.SendSMS);
turnGPSOn();
geo = new Geocoder(this, Locale.getDefault());
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
if (addresses != null)
{
address = addresses.get(0).getAddressLine(0) + " " + addresses.get(0).getAddressLine(1) + " " + addresses.get(0).getAddressLine(2);
tv1.setText(address);
}
else
tv1.setText("fail");
b1.setOnClickListener(this);
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.e("LM", "Not null");
double Lad = location.getLatitude();
double Long = location.getLongitude();
try {
addresses = geo.getFromLocation(Lad, Long, 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e("Long", String.valueOf(Long));
}
#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
}
}
what can i do to make the system wait till the LocationManger get the Location Coordinates and once it is available, show them in a text. Is threads a good idea and how it can be implemented? please provide tutorial or code with your answer. Thanks for your time and consideration.

Something like this should work:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_smsmy_location);
tv1 = (TextView) findViewById(R.id.ESMS);
tv2 = (TextView) findViewById(R.id.currentLocation);
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
double Lad = location.getLatitude();
double Long = location.getLongitude();
tv2.setText(Lad+", "+Long);
}
It's mostly just that within the onLocationChanged function you set the textView you want updated. So when the GPS location comes in (yes it can take a long time), it'll trigger this function and update your textView

Related

getFromLocation() returns null in Asynctask execute() method

I'm trying to make a weather app that uses Geocoder to get the current city, and then uses AsyncTask to get weather data from an api and then parse it. But when I input the current city into the AsyncTask execute() method, my app crashes:
private double latitude;
private double longitude;
String address;
LocationManager lm;
LocationListener ll;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
address = getAddress(latitude, longitude); // getAddress() is below
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
ll = new myLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}
private class myLocationListener implements LocationListener {
#Override
public void onLocationChanged(android.location.Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
String address = getAddress(latitude, longitude);
Task task = new Task(); // Task extends AsyncTask
task.execute(new String[] { address });
}
#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
}
public String getAddress(double lat, double lon) {
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
String ret = "";
try {
List<Address> addresses = geocoder.getFromLocation(
lat, lon, 10);
if (addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuffer str = new StringBuffer();
str.append(returnedAddress.getLocality());
str.append(",");
str.append(returnedAddress.getCountryName());
ret = str.toString();
} else {
ret = "No Address returned!";
}
} catch (IOException e) { // TODO Auto-generated catch block
e.printStackTrace();
ret = "Can't get Address!";
}
return ret;
}
I know for a fact that my getAddress() method works like it's supposed to. When I hardcode a city and state into the address field, it works like a charm. However, when I call my getAddress() method and set it to address, and then input it into execute(), the app crashes and it says that getFromLocation() returned null. Why is this happening? Is it the order of my code? Thank you for all answers in advance.
Make sure your GPS is enabled and you are not testing from the emulator. The provider will return null if it is not enabled as per the documentation. Since you need the current location and probably you do not want updates I will recommend you use requestSingleUpdate(). A better option will be to use the new LocationClient Class that is part of Google Services; its fused provider gets the best Location available for you.

gps location value dont print android

in this code i want to get the longitude and latitude and convert them to string
to use it on the screen
and sms
so how can i deal with it
should i do new class ? or this code is just modified
what should i do to make it work
i used all permitions for locations
public class MainActivity extends Activity implements LocationListener {
Location location; // location
LocationManager locationManager;
public String LatTxt;
public String LonTxt;
public Double latitude; // latitude
public Double longitude; // longitude
TextView latTextView = (TextView) findViewById(R.id.Latitude_Txt);
TextView lonTextView = (TextView) findViewById(R.id.Longitude_Txt);
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = (long) (1000 * 60 * 0.25); // 0.25
// minute
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES,locListener);
lonTextView.setText(" " + location.getLongitude());
latTextView.setText(" " + location.getLatitude());
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
latitude = location.getLatitude();
LatTxt = latitude.toString();
longitude = location.getLongitude();
LonTxt = longitude.toString();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
<TextView
android:id="#+id/Latitude_Txt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/white"
android:gravity="center_horizontal"
android:text="Latitude"
android:textColor="#android:color/black"
android:textSize="16sp" />
</LinearLayout>
Put
lonTextView.setText(" " + location.getLongitude());
latTextView.setText(" " + location.getLatitude());
to
#Override
public void onLocationChanged(Location location) {
}
You try to print location in: protected void onCreate(Bundle savedInstanceState) but location doesn't initiated.
BTW, add before lines:
lonTextView.setText(" " + location.getLongitude());
latTextView.setText(" " + location.getLatitude());
this code, to init old location
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES,this);
Criteria criteria = new Criteria();
locationManager.getLastKnownLocation(provider);
String provider = locationManager.getBestProvider(criteria, false);
location = locationManager.getLastKnownLocation(provider);
and remove your requestLocationUpdates
[EDIT]
public class MainActivity extends Activity implements LocationListener {
Location location; // location
LocationManager locationManager;
public String LatTxt;
public String LonTxt;
public Double latitude; // latitude
public Double longitude; // longitude
TextView latTextView = (TextView) findViewById(R.id.Latitude_Txt);
TextView lonTextView = (TextView) findViewById(R.id.Longitude_Txt);
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = (long) (1000 * 60 * 0.25); // 0.25
// minute
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locListener = this;
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES,locListener);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
latitude = location.getLatitude();
LatTxt = latitude.toString();
longitude = location.getLongitude();
LonTxt = longitude.toString();
lonTextView.setText(" " + location.getLongitude());
latTextView.setText(" " + location.getLatitude());
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
when a new GPS coordinate is received. The function onLocationChanged will be called. You should do your GPS coordinate manipulations in there

GPS coordinates are inaccurate on my Android Program

I am trying to get my current position of my phone via GPS in my program.
The Problem is, that either the coordinates are to inaccurate (only degrees) or no location is given. I programmed my third program now and each of them with a different tutorial, but it did not work as it should work there.
uses-permission are set, so that is not the answer ;)
So here is my code:
public class GpsActivity extends Activity{
private TextView latituteField;
private TextView longitudeField;
private TextView dateField;
private TextView timeField;
private LocationManager locationManager;
private String provider;
private LocationListener listener;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
dateField = (TextView) findViewById(R.id.tvdate);
timeField = (TextView) findViewById(R.id.tvtime);
GregorianCalendar g = new GregorianCalendar();
g.setTimeInMillis(System.currentTimeMillis());
DateFormat df = DateFormat.getInstance();
Date d = df.getCalendar().getTime();
dateField.setText(""+d.getDate()+"."+(d.getMonth()+1)+"."+(1980+d.getYear()));
timeField.setText(""+g.getTime().getHours()+"h "+g.getTime().getMinutes()+"m "+g.getTime().getSeconds()+"s");
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
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.");
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(""+lat+"//"+location.getAccuracy());
longitudeField.setText(""+lng+"//"+location.getProvider());
} else {
latituteField.setText("Provider not available");
longitudeField.setText("Provider not available");
}
listener = new MyLocationListener();
locationManager.requestLocationUpdates("gps" ,10000L, 10.0f, listener);
}
class MyLocationListener implements LocationListener{
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null){
latituteField.setText(("Lat: " + location.getLatitude()));
longitudeField.setText("LLong: " + location.getLongitude());
}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
Thanks for answering!
Rene
You are probably getting just a weak signal. You may use the android location API to get an approximate location.
Make sure that you stand outside and have a free view to the sky for getting a "good" signal. Don't stand next to buildings, etc. However even if you do that you won't get an accurate signal. Phone GPSs' are optimized for energy saving and not for accuracy. They won't put a too expensive chip on your phone as well...

Android MapActivity cannot retrieve location data

I have followed the HelloMapView tutorial for android, and added some code to capture my current location information and display in a textview.
I have tested these code in another program and it worked, it is able to display my longitude and latitude data when the launch that app. However when i copied the code into this MapActivity, it seems that i cannot get the location data.
Here's part of the code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapOverlays = mapView.getOverlays();
drawable = this.getResources().getDrawable(R.drawable.androidmarker);
itemizedOverlay = new HelloItemizedOverlay(drawable, this);
Button button1 = (Button)this.findViewById(R.id.button1);
tv1 = (TextView) this.findViewById(R.id.textView1);
button1.setOnClickListener(mScan);
latitude = 1.3831625;
longitude = 103.7727321;
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null)
location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
if (System.currentTimeMillis() - location.getTime() < 3000)
{
longitude = location.getLongitude();
latitude = location.getLatitude();
tv1.setText(Double.toString(longitude));
}
}
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 2000, 10, locationListener);
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
tv1.setText(Double.toString(latitude));
}
#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
}
};
Did you added proper permissions in Manifest? Like this
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Also please check your gps is enabled or working on ur deive.

Getting GPS data?

Inside
public class IAmHere extends Activity implements LocationListener {
i have
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#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
inside
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.iamhere);
i have
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List<String> providers = lm.getProviders(true);
/* Loop over the array backwards, and if you get an accurate location, then break out the loop*/
Location l = null;
for (int i=providers.size()-1; i>=0; i--) {
l = lm.getLastKnownLocation(providers.get(i));
if (l != null) break;
}
double[] gps = new double[2];
if (l != null) {
gps[0] = l.getLatitude();
gps[1] = l.getLongitude();
}
gpsString = (TextView)findViewById(R.id.gpsString);
String Data = "";
String koordinata1 = Double.toString(gps[0]);
String koordinata2 = Double.toString(gps[1]);
Data = Data + koordinata1 + " | " + koordinata2 + "\n";
gpsString.setText(String.valueOf(Data));
but seems it's not working? Why? I mean even emulator doesn't want to send GPS data - When I click "send" via UI or console, nothing happens...?
Thank you.
First, you implemented LocationListener on IAmHere, then did nothing with that interface.
Second, you are calling getLastKnownLocation(), but you are doing nothing to trigger Android to start collection location data on any provider.
These two problems are related.
Location services are off until something registers to get location data from them. Typically, this is via requestLocationUpdates() on LocationManager...which uses the LocationListener interface you implemented.
The recipe for using LocationManager is:
Register a LocationListener via requestLocationUpdates()
Unregister the LocationListener sometime (e.g., onDestroy()), so that you do not leak memory
When location fixes come into onLocationChanged(), do something useful
Here is a sample project that uses LocationManager and LocationListener in this fashion.

Categories

Resources