Android Location can not be entered to edit texts - android

I wrote a program to show my current location, Address etc in android phone. The API used is Android 2.2. Previously it worked fine in a MTS CDMA phone. It had an API of Android 2.3. It also works fine in emulator. Now. I have bought a Sony Ericsson Xperia Minipro and it also has Android 2.3. But the program will run on it. But the edit texts will not show anything. I use edit texts to display the values. They are not updated by the program at all. What can be the problem? Same program works fine in emulator and it shows location! Please help. I can paste the code below
public class TravelGuide extends Activity {
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES=1;
private static final long MINIMUM_TIME_BETWEEN_UPDATES=1000;
StringBuilder strReturnedAddress;
List<Address> addresses;
protected LocationManager locationManager;
static String videoId;
Double lat;
Double longd;
Address returnedAddress;
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
//Double latitude = location.getLatitude();
//Double longitude = location.getLongitude();
}
#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
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,new MyLocationListener());
showCurrentLocation();
}
public void showCurrentLocation()
{
Location location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location!=null)
{
TextView myLatitude = (TextView)findViewById(R.id.mylatitude);
TextView myLongitude = (TextView)findViewById(R.id.mylongitude);
TextView myAddress = (TextView)findViewById(R.id.myaddress);
String message=String.format("currentLocation\n Longitude:%1$s \n Latitude:%2$s",location.getLongitude(),location.getLatitude());
Toast.makeText(TravelGuide.this,message,Toast.LENGTH_LONG).show();
myLatitude.setText("Latitude: " + String.valueOf(location.getLatitude()));
myLongitude.setText("Longitude: " + String.valueOf(location.getLongitude()));
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(Double.valueOf(location.getLatitude()),
Double.valueOf(location.getLongitude()), 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
videoId = (returnedAddress.getAddressLine(1)).toString();
//sendAddress(videoId);
myAddress.setText(strReturnedAddress.toString());
}
else{
myAddress.setText("No Address returned!");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//test = "kovalam";
myAddress.setText("Canont get Address!");
}
}
}
public class MyLocationListener implements LocationListener
{
//private final Context MyLocationListener = null;
//double LATITUDE;
//double LONGITUDE;
TextView myLatitude;
TextView myLongitude;
TextView myAddress;
public void onLocationChanged(Location location)
{
//Context context = null;
myLatitude = (TextView)findViewById(R.id.mylatitude);
myLongitude = (TextView)findViewById(R.id.mylongitude);
myAddress = (TextView)findViewById(R.id.myaddress);
//String message=String.format("new Location\n Longitude:%1$s \n Latitude:%2$s",
//location.getLongitude(),location.getLatitude());
//Toast.makeText(TouristGuideActivity.this,message,Toast.LENGTH_LONG).show();
myLatitude.setText("Latitude: " + String.valueOf(location.getLatitude()));
myLongitude.setText("Longitude: " + String.valueOf(location.getLongitude()));
Geocoder geocoder = new Geocoder(TravelGuide.this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(Double.valueOf(location.getLatitude()),
Double.valueOf(location.getLongitude()), 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
videoId = (returnedAddress.getAddressLine(1)).toString();
//sendAddress(videoId);
//myAddress.setText(strReturnedAddress.toString());
myAddress.setText("Hello");
}
else{
myAddress.setText("No Address returned!");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
myAddress.setText("Canont get Address!");
}
}
public void onStatusChanged(String s, int i, Bundle b)
{
//Toast.makeText(TouristGuideActivity.this,"Provider status changed",Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s)
{
Toast.makeText(TravelGuide.this,"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s)
{
Toast.makeText(TravelGuide.this,"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
}

you are getting locaton object null,try put log in else condition..and the reason is you are fetching last known location which in not available in that phone some how..
so if its true..
Go to this answer here implement that code to get current location...and it will work fine.
If you are using GPS Provider to get Location,Its found that Its not so accurate to return you location object,Network Provider is better option According to me.

Related

How to get current Location of user ?

I made an application in android. I have to find current location of user i.e. City name
I use the below code, it could generate latitude & longitude but did not get name of the city.
My code is:
public class GetCurrentLocation extends Activity implements OnClickListener {
private LocationManager locationMangaer=null;
private LocationListener locationListener=null;
private Button btnGetLocation = null;
private EditText editLocation = null;
private ProgressBar pb =null;
private static final String TAG = "Debug";
private Boolean flag = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//if you want to lock screen for always Portrait mode
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);
editLocation = (EditText) findViewById(R.id.editTextLocation);
btnGetLocation = (Button) findViewById(R.id.btnLocation);
btnGetLocation.setOnClickListener(this);
locationMangaer = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
#Override
public void onClick(View v) {
flag = displayGpsStatus();
if (flag) {
Log.v(TAG, "onClick");
editLocation.setText("Please!! move your device to see the changes in coordinates."+"\nWait..");
pb.setVisibility(View.VISIBLE);
locationListener = new MyLocationListener();
locationMangaer.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10,
locationListener);
} else {
alertbox("Gps Status!!", "Your GPS is: OFF");
}
}
/*----------Method to Check GPS is enable or disable ------------- */
private Boolean displayGpsStatus() {
ContentResolver contentResolver = getBaseContext().getContentResolver();
boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(
contentResolver, LocationManager.GPS_PROVIDER);
if (gpsStatus) {
return true;
} else {
return false;
}
}
/*----------Method to create an AlertBox ------------- */
protected void alertbox(String title, String mymessage) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your Device's GPS is Disable")
.setCancelable(false)
.setTitle("** Gps Status **")
.setPositiveButton("Gps On",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// finish the current activity
// AlertBoxAdvance.this.finish();
Intent myIntent = new Intent(
Settings.ACTION_SECURITY_SETTINGS);
startActivity(myIntent);
dialog.cancel();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// cancel the dialog box
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
/*----------Listener class to get coordinates ------------- */
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(getBaseContext(),"Location changed : Lat: " + loc.getLatitude()
+ " Lng: " + loc.getLongitude(),Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " +loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " +loc.getLatitude();
Log.v(TAG, latitude);
/*----------to get City-Name from coordinates ------------- */
String cityName=null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName=addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude+"\n"+latitude +"\n\nMy Currrent City is: "+cityName;
editLocation.setText(s);
}
#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
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
}
How can I get name of the city i.e Current location of user ( like delhi, mumbai etc) ?
Try this way:
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
strReturnedAddress.append(returnedAddress.getLocality()).append("\n");
strReturnedAddress.append(areturnedAddress.getPostalCode()).append("\n");
strReturnedAddress.append(returnedAddress.getCountryName()).append("\n");
}
myAddress.setText(strReturnedAddress.toString());
For more information go to: http://developer.android.com/reference/android/location/Geocoder.html
try this-
Geocoder geocoder = new Geocoder(getActivity(),Locale.ENGLISH);
StringBuilder stringBuilder = new StringBuilder();
List<Address> addressList;
try {
addressList = geocoder.getFromLocation(Latitude, Longitude, 1);
if (addressList.size() > 0) {
Address address = addressList.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
stringBuilder.append(address.getAddressLine(i)).append("\n");
stringBuilder.append(address.getLocality()).append("\n");
stringBuilder.append(address.getPostalCode()).append("\n");
stringBuilder.append(address.getCountryName()).append("\n");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Don't forget to give 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" />
I would recommend to use google play services to vet the location http://developer.android.com/google/play-services/location.html
If your app can be installed in devices with no google play services check out this code https://github.com/BeyondAR/beyondar/tree/master/android/BeyondAR_Framework/src/com/beyondar/android/util/location and start with the location manager

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.

reverse geocoding not working

i written following code to get current location. although I m testing it in emulator with different latitude and longitude. But it cant convert the lattitude and longitude in real location.
public class LocationFindingActivity extends Activity {
/** Called when the activity is first created. */
EditText et;
LocationManager locationManager;
String provider;
LocationListener locationListener;
Location currentLocation;
String addressString="";
String longlattString="";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et=(EditText)findViewById(R.id.locationTXT);
locationManager =(LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = locationManager.getBestProvider(criteria, true);
currentLocation=locationManager.getLastKnownLocation(provider);
et.setText(addressString);
locationListener =new LocationListener() {
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
updateWithNewLocation(currentLocation);
}
};
updateWithNewLocation(currentLocation);
locationManager.requestLocationUpdates(provider, 2000, 10,locationListener)
}
private void updateWithNewLocation(Location location) {
if (location != null)
{
double lat = location.getLatitude();
double lng = location.getLongitude();
longlattstring="Lattitude :"+lat+"Longitude :"+lng;
Geocoder gc = new Geocoder(this, Locale.getDefault());
try
{
List<Address> addresses = gc.getFromLocation(lat, lng, 1);
StringBuilder sb = new StringBuilder();
//Toast.makeText(this, "Problem1", 2000).show();
if (addresses.size() > 0)
{
Address address = addresses.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
sb.append(address.getAddressLine(i)).append("\n");
sb.append(address.getLocality()).append("\n");
Toast.makeText(this, "Problem2", 2000).show();
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
}
addressString = sb.toString();
}
catch (IOException e)
{
Toast.makeText(this, "Problem Catch", 2000).show();
}
}
else
{
addressString = "No location found";
}
et.setText(addressString);
}
}
I am getting problem in this line
List addresses = gc.getFromLocation(lat, lng, 1);
the statement doesn't return anything.
It's a known bug which they never fixed see service not avavilable.I think you will find that it works in the the API level 7 emulator.

How to track location through GPS in android application

I am working on development of android game application. I want to judge location of players of game. I want that details like pincode, city name,country name, geo cordinates, accuracy etc.
public class GPSLocationListener implements LocationListener {
Context context;
#Override
public void onLocationChanged(Location location2) {
location2.getLatitude();
location2.getLongitude();
#Override
public void onProviderDisabled(String provider) {
AlertPopup.displayPopup(context, "GPS Disabled");
}
#Override
public void onProviderEnabled(String provider) {
AlertPopup.displayPopup(context, "GPS Enabled");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
}
but not able to get all data which i want
Assuming that you are aware how to use GPS in android. Here is how to get the information you want.
Pincode, city name, country name
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder gc = new Geocoder(this, Locale.getDefault());
try
{
List<Address> addresses = gc.getFromLocation(latitude,
longitude, 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0)
{
Address address = addresses.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
sb.append(address.getAddressLine(i)).append("\n");
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
}
addressString = sb.toString();
} catch (IOException e) {
}
}
else
{
addressString = "No where";
}
Geo cordinates, accuracy
location.getLatitude()
and
location.getAccuracy()

Reverse Geocoding in android [duplicate]

This question already has answers here:
Geocoder.getFromLocation throws IOException on Android emulator
(7 answers)
Closed 6 months ago.
In the code below, I am getting the following exception
NO SERVICE AVAIALBLE
public class ds extends Activity {
LocationManager locationManager;
double lati,longi;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String location_context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(location_context);
testProviders();
}
public void testProviders() {
TextView tv = (TextView)findViewById(R.id.myTextView);
StringBuilder sb = new StringBuilder("Enabled Providers:");
List<String> providers = locationManager.getProviders(true);
for (String provider : providers)
{
locationManager.requestLocationUpdates(provider, 1000, 0,new LocationListener()
{
public void onLocationChanged(Location location) {}
public void onProviderDisabled(String provider){}
public void onProviderEnabled(String provider){}
public void onStatusChanged(String provider, int status,
Bundle extras){}
});
sb.append("\n").append(provider).append(":");
Location location = locationManager.getLastKnownLocation(provider);
if (location != null)
{
double lat = location.getLatitude();
double lng = location.getLongitude();
sb.append(lat).append(",").append(lng);
lati=lat;
longi=lng;
Geocoder gcd = new Geocoder(ds.this, Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(lati, longi, 1);
if (addresses.size() > 0)
} catch (IOException e) {
Toast.makeText(ds.this, "hi exception", 5000).show();
}
}
else {
sb.append("No Location");
}
}
tv.setText(sb);
}
}
Code for Reverse Geocoding , you can pass the lattitude and longitude according to your requirement......
public class MainActivity extends FragmentActivity {
static final LatLng DELHI = new LatLng(39.6985207, -104.8954315);
GoogleMap map;
Button btn_geo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activitymain);
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
btn_geo=(Button)findViewById(R.id.btn_getAddress);
map.addMarker(new MarkerOptions().position(DELHI).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
// Move the camera instantly to hamburg with a zoom of 15.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(DELHI, 15));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
btn_geo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Geocoder myLocation = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
if(myLocation.isPresent())
{
List<Address> addresses=null ;
addresses = myLocation.getFromLocation(39.6985207, -104.8954315, 1);
System.out.println(".................."+addresses);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0)
{
Address address = addresses.get(0);
sb.append(address.getAddressLine(0)).append("\n");
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
Toast.makeText(getApplicationContext(), sb,Toast.LENGTH_LONG).show();
}
}
else
Toast.makeText(getApplicationContext(), "Not present",Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}

Categories

Resources