I'm working on GPS based application that gets the address based on GPS provider but sometimes it doesn't work due to lack of signal like as at underground parking or similar places. So in such situtation i want to take the address through Network provider and send SMS via sendSMS() method. It has to repeat every 10 mints and call the sendSMS() method with updated Location.
The code for getting GPS location is below could you please suggest me to edit it according to my need?
public class WPGActivity extends Activity {
ImageButton start;
Button login;
String ADDRESS, LOCATION;
TextView addressText, locationText;
Location currentLocation;
double currentLatitude;
double currentLongitude;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
start=(ImageButton)findViewById(R.id.imageButton1);
login=(Button)findViewById(R.id.button1);
addressText = (TextView)findViewById(R.id.addressText);
locationText = (TextView)findViewById(R.id.locationText);
myLocation();
// if(ACTIVE_MODE==1) startApp();
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
getAddress(); // to get address
sendSMS(); // to send sms
sendEmail(); // to send email
}
});
}
public void myLocation(){
LocationManager locationManager =
(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateLocation(location);
}
public void onStatusChanged(
String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000*60*5, 30, locationListener);
}
public void getAddress(){
try{
Geocoder gcd = new Geocoder(this, Locale.getDefault());
List<Address> addresses =
gcd.getFromLocation(currentLatitude, currentLongitude,100);
if (addresses.size() > 0) {
StringBuilder result = new StringBuilder();
for(int i = 0; i < addresses.size(); i++){
Address address = addresses.get(i);
int maxIndex = address.getMaxAddressLineIndex();
for (int x = 0; x <= maxIndex; x++ ){
result.append(address.getAddressLine(x));
result.append(",");
}
result.append(address.getLocality());
result.append(",");
result.append(address.getPostalCode());
result.append("\n\n");
}
ADDRESS = result.toString();
addressText.setText(ADDRESS);
}
}
catch(IOException ex){
ADDRESS= ex.getMessage().toString();
addressText.setText(ADDRESS);
}
}
void updateLocation(Location location){
currentLocation = location;
currentLatitude = currentLocation.getLatitude();
currentLongitude = currentLocation.getLongitude();
locationText.setText(LOCATION);
}
}
Related
In my project I'm trying to get the latitude, the longitude and the address but for some reason I can't get it appears the message Location not available everytime.
In the manifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
Have someone had this issue before?
This is my class:
public class GEO extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private TextView addressField; //Add a new TextView to your activity_main to display the address
private LocationManager locationManager;
private String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.geo);
latituteField = (TextView) findViewById(R.id.txt1);
longitudeField = (TextView) findViewById(R.id.txt2);
addressField = (TextView) findViewById(R.id.txt3);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, true);
Log.d("SomeTag", provider);
Log.d("SomeTag", String.valueOf(locationManager.isProviderEnabled(provider)));
Location location = locationManager.getLastKnownLocation(provider);
String locationProvider = LocationManager.GPS_PROVIDER;
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
if (lastKnownLocation != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(lastKnownLocation);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
addressField.setText("Location not available");
}
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
//You had this as int. It is advised to have Lat/Loing as double.
double lat = location.getLatitude();
double lng = location.getLongitude();
Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
StringBuilder builder = new StringBuilder();
try {
List<Address> address = geoCoder.getFromLocation(lat, lng, 1);
int maxLines = address.get(0).getMaxAddressLineIndex();
for (int i=0; i<maxLines; i++) {
String addressStr = address.get(0).getAddressLine(i);
builder.append(addressStr);
builder.append(" ");
}
String fnialAddress = builder.toString(); //This is the complete address.
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
addressField.setText(fnialAddress); //This will display the final address.
} catch (IOException e) {}
catch (NullPointerException e) {}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
I do run my project with a phone
It could be that address.get(0) is null in
List<Address> address = geoCoder.getFromLocation(lat, lng, 1);
int maxLines = address.get(0).getMaxAddressLineIndex();
And you are catching the NPEs, so it might be difficult to identify exactly why you are not getting the expected results.
Something like this might help:
try {
List<Address> addresses = geoCoder.getFromLocation(lat, lng, 1);
Address firstAddress = addresses.get(0);
if(firstAddress != null) {
int maxLines = firstAddress.getMaxAddressLineIndex();
for (int i = 0; i < maxLines; i++) {
String addressStr = firstAddress.getAddressLine(i);
builder.append(addressStr);
builder.append(" ");
}
addressField.setText(builder.toString()); //This will display the final address.
}
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
} catch (IOException e) {
e.printStackTrace();
}
Also, from http://developer.android.com/reference/android/location/Geocoder.html
Try checking isPresent
public static boolean isPresent ()
Added in API level 9
Returns true if the Geocoder methods getFromLocation and getFromLocationName are implemented. Lack of network connectivity may still cause these methods to return null or empty lists.
my following coding for getting current address means location is failed if i try to set address to the TextBox but when i put that code inside a onClick event of Button that works properly
This is Coding is Working When it is inside a onCLick event
import java.io.IOException;
import java.util.*;
import android.widget.*;
import android.view.View;
import android.view.View.OnClickListener;
import android.app.Activity;
import android.os.Bundle;
import android.location.*;
import android.content.*;
public class location extends Activity {
Button addressButton;
TextView addressText;
Location currentLocation;
double currentLatitude;
double currentLongitude;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
addressText = (TextView)findViewById(R.id.addressText);
addressButton = (Button)findViewById(R.id.addressButton);
this.addressText.setText("ready");
LocationManager locationManager =
(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateLocation(location);
}
public void onStatusChanged(
String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
this.addressButton.setOnClickListener(new OnClickListener() {
public void onClick(View v){
try{
Geocoder gcd = new Geocoder(location.this, Locale.getDefault());
List<Address> addresses =
gcd.getFromLocation(currentLatitude, currentLongitude,100);
StringBuilder result = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
int maxIndex = address.getMaxAddressLineIndex();
for (int x = 0; x <= maxIndex; x++ ){
result.append(address.getAddressLine(x));
//result.append(",");
}
}
addressText.setText(result.toString());
Intent send_add = new Intent();
send_add.putExtra("address",result.toString());
}
catch(IOException ex){
addressText.setText(ex.getMessage().toString());
}
}
});
}
void updateLocation(Location location){
currentLocation = location;
currentLatitude = currentLocation.getLatitude();
currentLongitude = currentLocation.getLongitude();
}}
This is Coding not Working here i dont want to use Button when i open this activity it must display direct address means it should be Set to the Textview
public class location extends Activity {
Button addressButton;
TextView addressText;
Location currentLocation;
double currentLatitude;
double currentLongitude;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
addressText = (TextView)findViewById(R.id.addressText);
addressButton = (Button)findViewById(R.id.addressButton);
this.addressText.setText("ready");
LocationManager locationManager =
(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateLocation(location);
}
public void onStatusChanged(
String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
try{
Geocoder gcd = new Geocoder(location.this, Locale.getDefault());
List<Address> addresses =
gcd.getFromLocation(currentLatitude, currentLongitude,100);
StringBuilder result = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
int maxIndex = address.getMaxAddressLineIndex();
for (int x = 0; x <= maxIndex; x++ ){
result.append(address.getAddressLine(x));
//result.append(",");
}
}
addressText.setText(result.toString());
Intent send_add = new Intent();
send_add.putExtra("address",result.toString());
}
catch(IOException ex){
addressText.setText(ex.getMessage().toString());
}
}
void updateLocation(Location location){
currentLocation = location;
currentLatitude = currentLocation.getLatitude();
currentLongitude = currentLocation.getLongitude();
}}
Here i just made a small change but not working
I have updated your code and it is working correct now :
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
currentLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); //added by me
// Geocoder gcd = new Geocoder(location.this, Locale.getDefault());
try{
// Geocoder gcd = new Geocoder(location.this, Locale.getDefault());
//List<Address> addresses =
// gcd.getFromLocation(currentLatitude, currentLongitude,100);
List<Address> addresses = new Geocoder(location.this,Locale.getDefault()).getFromLocation(currentLocation.getLatitude(), currentLocation.getLongitude(), 1); // changed
StringBuilder result = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
int maxIndex = address.getMaxAddressLineIndex();
for (int x = 0; x <= maxIndex; x++ ){
result.append(address.getAddressLine(x));
//result.append(",");
}
}
addressText.setText(result.toString());
Intent send_add = new Intent();
send_add.putExtra("address",result.toString());
}
catch(IOException ex){
addressText.setText(ex.getMessage().toString());
}
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.
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()
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();
}
}
});
}
}