How to find user location based on EditText value - android

I am trying to get user's city from EditText and then check if it is valid or not. If there is a little typo, then I want to correct it on the EditText and then show it back to user.
I have been searching for this for quite some time but what I am getting is to get user current location and then get its location according to lat and long values. But I don't want to do this.
Here's what I am doing right now, but I don't want to do it this way
userDataFrag.loc.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onStatusChanged(String provider,
int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
userLat = location.getLatitude();
userLong = location.getLongitude();
Geocoder geocoder = new Geocoder(getActivity(),
Locale.getDefault());
List<Address> addresses;
try {
addresses = geocoder.getFromLocation(userLat,
userLong, 1);
CityName = addresses.get(0).getAddressLine(0);
StateName = addresses.get(0).getAddressLine(1);
CountryName = addresses.get(0).getAddressLine(2);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Can any one suggests me a better way to do it?

Related

Hot to collect the latitude and longitude values when i dial a particular on my phone dial pad

public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
String phonenum = intent.getExtras().getString(Intent.EXTRA_PHONE_NUMBER);
if (phonenum.equals("111")) {
locationmanager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationmanager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationlistener);
Toast.makeText(context, "The Gps values are..." + lon, Toast.LENGTH_LONG).show();
}
}
}
private static LocationListener locationlistener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
lat = Double.toString(location.getLatitude());
lon = Double.toString(location.getLongitude());
}
};
hi,
when i dial 111 on my dial pad my app which is pre installed on my device should toast the latitude and logitude values.I tried a sample app which displays toast message on dial of 111 making use of broadcast receiver.Above is the code which i tried.Can any help me how to get the latitude and logitude values from this fucntion.
private Location getLastBestLocation() {
Location locationGPS = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location locationNet = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
long GPSLocationTime = 0;
if (null != locationGPS) { GPSLocationTime = locationGPS.getTime(); }
long NetLocationTime = 0;
if (null != locationNet) {
NetLocationTime = locationNet.getTime();
}
if ( 0 < GPSLocationTime - NetLocationTime ) {
return locationGPS;
}
else {
return locationNet;
}}

Show Latitude and Longitude as soon as LocationManger gets it

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

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.

onLocationChanged is not working on real device

Now I am working with location based app and my problem is that the location is not updated on the real device. That is the onLocationChanged not working on real device. But fine on emulator.
locmngr=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
loclis =new MyLocationListner();
our_location=locmngr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
locmngr.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0,loclis);
public class MyLocationListner implements LocationListener{
#Override
public void onLocationChanged(Location location)
{
// TODO Auto-generated method stub
L1=location.getLatitude();
L2=location.getLongitude();
String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
// Toast.makeText(getApplicationContext(), currentDateTimeString, Toast.LENGTH_SHORT).show();
DatabaseHandlerActivity db = new DatabaseHandlerActivity(getApplicationContext());
db.addLocation(new Locations_viewer(L1.toString(), L2.toString(), currentDateTimeString));
Toast.makeText(getApplicationContext(), "New Location "+"Latitude ="+L1+
" Longitude ="+L2, Toast.LENGTH_LONG).show();
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = df.format(c.getTime());
ParseUser.getCurrentUser().put("Latitude", L1.toString());
ParseUser.getCurrentUser().put("Longitude", L2.toString());
ParseUser.getCurrentUser().put("Time", formattedDate);
ParseUser.getCurrentUser().saveInBackground();
// Toast.makeText(getApplicationContext(), "Latitude ="+L1, Toast.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(), "Longitude ="+L2, Toast.LENGTH_LONG).show();
}
#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
}
}
Please help me.
I just used NETWORK_PROVIDER instead of GPS_PROVIDER. Because GPS is not available in all locations. In my case it solved my problem perfectly. We just need an active internet connection in our mobile.

Not getting zipcode from Latitude and Longitude

I am trying to find out the latitude and longitude in an Android application. The code that I am using is as follows:-
protected int findZipCode() {
LocationManager lm = (LocationManager) getApplicationContext()
.getSystemService(Context.LOCATION_SERVICE);
LocationListener listener = new MyLocationListener();
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000,
1000, listener);
if (zipCode == null) {
return 0;
} else {
return Integer.parseInt(zipCode);
}
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null) {
Geocoder geo = new Geocoder(getApplicationContext());
List<Address> addr = null;
try {
addr = geo.getFromLocation(location.getLatitude(),
location.getLatitude(), 5);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
zipCode = addr.get(0).getPostalCode();
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
But this code seems to always return a null value for the zipcode. Any help would be great.
Thanks in advance!!
As your MyLocationListener is running in parallel at that point your zipCode is null therefore you are getting 0 value.
Fix
You can wait the MyLocationListener to complete and pass a interface method to this listener and on the complete of this function you can call that method.
What are you doing dude?
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000,1000, listener);
The above line is a asynchronus call, listener will be called when you get a position fix.
You can't check for zipcode right after this line.
In listner when you get the value of zipcode, implement some interface/callback which will give you the value of zipcode in your activity or where ever you want.

Categories

Resources