Android onCreate sequencing issue - android

I'm trying to build a string with origin and destination gps coordinates for google mapping purposes. The first thing that I need to do is to get the gps coordinates of my current location, since this is the origin point. Then, I need to concatenate these coordinates into a larger string that I use to get directions.
I have code that gets these coordinates, and also code that concatenates them into the correct string format. However, my problem is that my string building code is running first, which is leaving me with null pointer issues since the string is referencing gps coordinates that haven't processed yet.
Here it is. The gotLocation() method comes from implementing advice in this post:
Public class DirectionsActivity extends Activity {
String myLat, myLng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Parser parser;
LocationResult locationResult = new LocationResult(){
#Override
public void gotLocation(final Location location){
try {
Double lat = location.getLatitude();
Double lng = location.getLongitude();
if (lat != 0.0 && lng != 0.0) {
myLat = Double.toString(lat);
myLng = Double.toString(lng);
String gps_location = myLat + " " + myLng;
Toast.makeText(getBaseContext(), "First Message", Toast.LENGTH_SHORT).show();
}
}catch (Exception e) {
}
}
};
MyLocation myLocation = new MyLocation();
myLocation.getLocation(this, locationResult);
Toast.makeText(getBaseContext(), "Second Message", Toast.LENGTH_LONG).show();
buildString();
setContentView(R.layout.activity_directions);
}
The toast output when I run this is "Second Message" followed by "First Message". They should display in the opposite order.

Getting a location is an asynchronous operation, you don't have control on the time at which you get the answer from the system.
How would you be sure to find a satellite or cell phone mat before your toast appears ? :)

Related

Coordinates are not submitted

So I'm trying to get the actual coordinates of the smartphone and then submit it. For this purpose I am working with a (non-optimal) email solution. I want to get the coordinates and then submitting them by email.
If I press the button, it should get the coordinates and then putting them into mail.
Somehow I only get 0.0 into the email client, which should be the default values.
Anyway, here is my relevant code:
I initialise lat and lon with double in the public class.
public LatLng getLocation()
{
// Get the location manager
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(bestProvider);
finden
try {
lat = location.getLatitude();
lon = location.getLongitude();
//überschreiben der Variabeln lon & lat funktioniert
return new LatLng(lat, lon);
}
catch (NullPointerException e){
e.printStackTrace();
return null;
}
}
And this is my button.
final Button button = (Button) findViewById(R.id.addbutton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
getLocation();
Intent i = new Intent(Intent.ACTION_SENDTO);
//i.setType("message/rfc822");
i.setData(Uri.parse("mailto:"));
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"adress#example.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "Subject - New Location was added");
i.putExtra(Intent.EXTRA_TEXT , "Latitude: " + lat + " Longitude: " + lon " );
try {
startActivity(i);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MapsActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
});
So what is my fault? The app is running, but it wont get the coordinates.
Have you provided the ACESS_FINE_LOCATION in the manifest file? You need this permission to access location.
You need to add this in the manifest file.
Edit:
Look, these days fused location provider is being used and there do come some instances where you don't get the permission and location doesn't come up. Read this file which is a basic example for retrieving location -
https://github.com/googlesamples/android-play-location/blob/master/BasicLocationSample/app/src/main/java/com/google/android/gms/location/sample/basiclocationsample/MainActivity.java
Also, this is the guide for it -
https://developer.android.com/training/location/retrieve-current.html

Latitude and Longitude always getting zero (GPS and TimerTask)

Below is the code I used for getting longitude and latitude within a timertask.
public void onClick(View v) {
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
try {
gpt = new GPSTracker(MainActivity.this);
System.out.println("Internet is present");
setContentView(R.layout.tracklayout);
TimerTask myTask = new TimerTask() {
#Override
public void run() {
try {
Log.d("flow", "" + "task()");
gpt = new GPSTracker(MainActivity.this);
lc = gpt.getLocation();
if (gpt.canGetLocation()) {
double latitude = gpt.getLatitude();
double longitude = gpt.getLongitude();
Log.d("latitude", "" + latitude);
Log.d("longitude", "" + longitude);
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Reached.. ",Toast.LENGTH_LONG).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
};
Timer myTimer = new Timer();
myTimer.schedule(myTask, 3000, 30000);
} catch (Exception e) {
e.printStackTrace();
}
} else {
alert.showAlertDialog(MainActivity.this,"Mobile Data is Off","Please Turn On mobile data to proceed", false);
}
}
});
Latitude and longitude are always getting zero even I manually entered co-ordinates through DDMS. There no problem with the code of GPSTracker. Outside timertask it worked fine. What is the problem with this code. Anyone please help
As you are using GPSTracker ,If GPS is not working than you can not have lat and long values for sure, you can't get an accurate location. It may take few minutes or seconds because it depends on lot of constraints like yours position inside building, weather , you device hardware quality etc as you are using sattelite to have locations, So we can say thatit depends on the device and the environment settings ( weather, Location under the sky/inside or outside building,device hardware quality etc as an example).
Why you are not using NETWORK_PROVIDER ?? if you can...
If you want to get a coarse location faster with program than you can get the location using NETWORK_PROVIDER, which isn't that accurate but can get you the location very faster.
Visit for examples
http://www.vogella.com/tutorials/AndroidLocationAPI/article.html
http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/
http://developer.android.com/guide/topics/location/strategies.html
Don't use timertask. Implement LocationListener with that activity. Write the codes in the timertask to OnLocation changed. Not needed to run in paricular time interval because we get the same data if we are in same location.

Can't get current device location

I am trying to get current location of my android phone and display the longitude and latitude in a toast. Here is a function I wrote. While debugging the code I see that the control never goes inside onLocationChanged function.
From the following android documentation it looks like, when I call "locationMgr.requestLocationUpdates", it should call the callback function onLocationChanged. But that does not seem to happen in my code.
http://developer.android.com/training/basics/location/currentlocation.html
I checked my phone has GPS turned on. I can not figure out what is wrong in the following code. Please help.
public void getCurrentLocation(){
LocationManager locationMgr;
locationMgr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// A new location update is received. Do something useful with it
String latitude = "latitude: " + location.getLatitude();
String longitude = "longitude: " + location.getLongitude();
String toastString = "location is" + latitude + "," +longitude;
Toast.makeText( getApplicationContext(),toastString,Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
// No code here
}
#Override
public void onProviderEnabled(String provider) {
// No code here
}
#Override
public void onStatusChanged(String provider, int status,Bundle extras)
{
// No code here
}
};
locationMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER,0, 0, listener);
}
I also have following two lines in my Manifest file.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Thank you for your help.
I am using Eclipse and my phone(OS: Thuderbolt) has API level 15, target 4.0.4.
There are several reasons that you are not getting location.
1.) If you are trying to get location on emulator. Then you have to manually push the coordinates using DDMS.
2.) If You are checking it on device and still you are not getting location. Then as you said that you are expecting it from GPS. Then you should have Clear sky view to get that. As GPS receiver dont work under roofs or under some hinderances. They must have sky view.
3.) You can get location from using wi-fi or cell-Tower. Also you can opt for Last known location if location accuracy is not as much important.
What i think is that may be second point will resolve your problem.
The problem was google-play-services library.
I had to download the library code and compile it in eclipse. Then I added the path to the library in my project. This solved the problem.
Earlier I had included the google-play-services .jar file in my project, but it was not working. Not sure why.
Here is example i wrote that uses LocationManager to get the location data every two minutes. Its not perfect but should be sufficient to solve your issue: It can be found here
Focus on:
#Override
public void onLocationChanged(final Location location) {
this.location=location;
final Handler handler = new Handler();
Timer ourtimer = new Timer();
TimerTask timerTask = new TimerTask() {
int cnt=1;
public void run() {
handler.post(new Runnable() {
public void run() {
Double latitude = location.getLatitude();
Double longitude = location.getLongitude();
Double altitude = location.getAltitude();
Float accuracy = location.getAccuracy();
textView.setText("Latitude: " + latitude + "\n" + "Longitude: " + longitude+ "\n" + "Altitude: " + altitude + "\n" + "Accuracy: " + accuracy + "meters"+"\n" + "Location Counter: " + cnt);
try {
jsonData = new JSONObject();
jsonData.put("Latitude", latitude);
jsonData.put("Longitude", longitude);
jsonData.put("Altitude", altitude);
jsonData.put("Accuracy", accuracy);
System.out.println(jsonData.toString()); //not required, for testing only
if(url!=null) {
new HttpPostHandler().execute();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cnt++;
}
});
}};
ourtimer.schedule(timerTask, 0, 120000);

Making the phone silent on nearing a particular location

I am making an android application to show the position of a user on a map, along with the users current longitude and latitude, I have also used reverse geocoding to show the address of the android device. Now I plan to add a feature that if the user is near a particular place the phone automatically switches to silent mode, for this I have made a function to check whether the phone is already silent or not. Now I want to make another one, which puts the phone in silent mode on nearing a particular location.
The method which I have made to make the phone go silent on nearing a particular location is
public void changeToSilent(Location location){
if(distanceTo(xxxx)<100)
{
if(mPhoneIsSilent==true){
}
else
{
mPhoneIsSilent = true;
mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
}
}
}
Now I am calling this method in another function, which is....
public void onLocationChanged(Location location)
{
Log.d(TAG, "onLocationChanged with location " + location.toString()); Stringtext=String.format("Lat:\t%f\nLong:\t%f\nAlt:\t%f\nBearing:\t%f",location.getLatitude(),location.getLongitude(), location.getAltitude(), location.getBearing());
this.locationText.setText(text);
changeToSilent(location);
try {
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 10);
for (Address address : addresses) {
this.locationText.append("\n" + address.getAddressLine(0));
}
int latitude = (int)(location.getLatitude() * 1000000);
int longitude = (int)(location.getLongitude() * 1000000);
GeoPoint point = new GeoPoint(latitude,longitude);
mapController.animateTo(point);
} catch (IOException e) {
Log.e("LocateMe", "Could not get Geocoder data", e);
}
}
Now I am calling the above function in the oncreate method. Now suppose I know the latitude and longitude of the place near which the phone should go to silent.
What I want to know is, what do I have to write in place of xxxx in the changetosilent method?
You can use the AudioManager to change the system volume levels.
here is an example:
AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
//am.setStreamVolume(AudioManager.STREAM_MUSIC,6,0); //<-- use this one to set the volume
am.setRingerMode(AudioManager.RINGER_MODE_SILENT); //<-- to put on mute.
EDIT: Get a Location object and use loc.distanceBetween();

problem in showing latitude longitude location in an android app

Following is the code which i am using to find the latitude longitude and location of a place in my app, but it always show no location found
I have added the permissions in manifest file
{
LocationManager locManager;
setContentView(R.layout.main);
locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000L,500.0f, locationListener);
Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null)
{
String param = (String)locManager.getProviders(true).get(0);
Location loc = locManager.getLastKnownLocation(param);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
}
}
private void updateWithNewLocation(Location location)
{
TextView myLocationText = (TextView)findViewById(R.id.widget52);
String latLongString = " ";
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);
}
private final LocationListener locationListener = new LocationListener()
{
public void onLocationChanged(Location location)
{
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider)
{
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider)
{
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
};
}
pls help me...
I've put your code in an Android project and ran it on the emulator and it seems to be working fine.
I would change the code to first check for a lastknown location, and after that check for location updates.
Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
If that location is null, or too stale (timestamp) for your needs, you can start requesting location updates. (currently, you're first requesting location updates from the GPS, and then decide to retrieve its lastknownlocation). This might cause the location manager to stop querying the GPS.
Also you need to ensure the following is in place :
For GPS Provider, make sure the following permission is put in the manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Ensure the GPS is turned on that you have sufficient GPS coverage.
Do this by checking for the GPS icon in your Notification bar
Test on a real device
Although testing GPS location listeners works partly through the emulator, the behavior of an actual device will always be different.
Debug on the emulator
Basic GPS testing can be done using the emulator. Put a breakpoint in your locationlistener, and use the DDMS perspective to send some GPS coordinates to your AVD image.
#Siva, your problem is with the UI thread, as your updates are from different thread.
To verify if this is the UI problem, put a toast or Log cat the message when you receive an update.
Once you know that UI problem, then try using Handler to postInvalidate() the UI.

Categories

Resources