Server Switching In Android - android

"I need to switch Base URL based on a user's Location and change other UI components".
I tried throughout the Build Config but I didn't find anything that seems to work.

First you have to add servers to strings.xml file then you can use this one to get location country name after that in switch case you can change the server
#Override
protected void onResume() {
String country_name = null;
LocationManager lm =
(LocationManager)getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
Geocoder geocoder = new Geocoder(getApplicationContext());
for(String provider: lm.getAllProviders()) {
#SuppressWarnings("ResourceType") Location location = lm.getLastKnownLocation(provider);
if(location!=null) {
try {
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if(addresses != null && addresses.size() > 0) {
country_name = addresses.get(0).getCountryName();
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Toast.makeText(getApplicationContext(), country_name, Toast.LENGTH_LONG).show();
}

Related

unable to get both latitude and longitude from address, I get one of them either latitude or longitude

I am working on an app which works with latitude and and longitude after a user input an address. I'm utilizing Geocoder to get the latitude and longitude from the Input address. But the issue is both are returned with associated address from the Geocoder but I'm only able to read one of them. following is the code I'm using:
Geocoder geocoder = new Geocoder(this);
List<Address> addresses;
double[] cordinates = new double[2];
try {
addresses = geocoder.getFromLocationName(locName, 1);
if (addresses.size() > 0) {
cordinates[0] = addresses.get(0).getLatitude();
cordinates[1] = addresses.get(0).getLongitude();//unable to get this one
return cordinates;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
in the above cases I'm able to get latitude but unable to get the longitude. I known this after debugging. Now when I swap them like
cordinates[1] = addresses.get(0).getLongitude();
cordinates[0] = addresses.get(0).getLatitude();
Now I get Longitude but not the latitude.
what is the problem here?
This is working fine. Since you are debugging your code with breakpoints when it encounters the
return cordinates; it goes to
return null;
It only happens while debugging. It always returns the correct value. You can check returned values by inserting a log statement.
{
.....
double[] coordinates = getLongLat("Your address");
Log.wtf(TAG,"Lat:"+coordinates[0]+" Long:"+coordinates[1]);// This will log the correct values
.....
}
public double[] getLongLat(String address){
Geocoder geocoder = new Geocoder(this);
List<Address> addresses;
double[] cordinates = new double[2];
try {
addresses = geocoder.getFromLocationName(address, 1);
if (addresses.size() > 0) {
Address address1 = addresses.get(0);
cordinates[0] = address1.getLatitude();
cordinates[1] = address1.getLongitude();
return cordinates;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Try this working code :
AutoCompleteTextView acGooglePlaces = (AutoCompleteTextView) findViewById(R.id.ac_edit_my_event_places);
acGooglePlaces.setAdapter(new GooglePlacesAutocompleteAdapter(GooglePlaces.this, R.layout.auto_complete_text_layout));
acGooglePlaces.requestFocus();
btnSearch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
List<Address> returnedaddresses = geoCoder.getFromLocationName(acGooglePlaces.getText().toString(),1);
if(!returnedaddresses.isEmpty()){
String latForVol = String.valueOf(returnedaddresses.get(0).getLatitude());
String longForVol = String.valueOf(returnedaddresses.get(0).getLongitude());
Log.e("Lat", latForVol);
Log.e("Long", longForVol);
Log.e("Location", acGooglePlaces.getText().toString());
}else {
Log.e("Check", "Please give the correct address");
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
public static LatLng reverseGeocoding(Context context, String locationName){
if(!Geocoder.isPresent()){
Log.w("zebia", "Geocoder implementation not present !");
}
Geocoder geoCoder = new Geocoder(context, Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocationName(locationName, 1);
} catch (IOException e) {
Log.d(Geocoding.class.getName(), "not possible finding LatLng for Address : " + locationName);
}
if(addresses.size() > 0){
Log.d("zebia", "reverse Geocoding : locationName " + locationName + "Latitude " + addresses.get(0).getLatitude() );
return new LatLng(addresses.get(0).getLatitude(), addresses.get(0).getLongitude());
}else{
//use http api
}
return null;
}

Get user country by using Wi-Fi

I am looking for a way to get the user's country by using the Wi-Fi.
So far I have managed to do it using TelephonyManager and the SIM card, like this
TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
String s = telephonyManager.getSimCountryIso();
This works ok, but the problem is, the user may not have a sim card (a tablet), so I also need to be able to determine the country by using the Wi-Fi they are connected to.
I tried this code, but its not working as I want it to, I simply want a country code, like US, UK, DE, instead this method returns GPS coordinates...
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
Log.v("LOCATION", location.getProvider());
}
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);
How can I get the country using the Wi-Fi?
You require to do reverse geocoding, i.e. converting location you get to address. For this you can use Geocoder
Geocoder gcd = new Geocoder(this, Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(location.getLatitude(), location.getLongitude(), 1); //1 - is number of result you want you write it any integer value. But as you require country name 1 will suffice.
if (addresses.size() > 0)
System.out.println(addresses.get(0).getCountryName());
} catch (IOException e1) {
e1.printStackTrace();
} catch (Exception e1) {
e1.printStackTrace();
}
This can be done with GeoCoder, heres a snippet of code for checking WiFi and obtaining location info:
public Location getLocation() {
try {
// any location
// Getting network status
Log.e("GPS Service", "Get Location Called");
isNetworkEnabled = mLocationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Log.e("GPS Service", String.valueOf(isNetworkEnabled));
if (isNetworkEnabled) {
Log.e("GPS Service", "Yay Wifi Enabled");
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, this);
if (mLocationManager != null) {
mLocation = mLocationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (mLocation != null) {
Log.e("GPS Service", "Yay Location");
mLatitude = mLocation.getLatitude();
mLongitude = mLocation.getLongitude();
isLocationAvailable = true; // setting a flag that
// location is available
return mLocation;
}
}
}
// If reaching here means, we were not able to get location neither
// from GPS not Network,
if (!isGPSEnabled) {
// so asking user to open GPS
//askUserToOpenGPS();
}
} catch (Exception e) {
e.printStackTrace();
}
// if reaching here means, location was not available, so setting the
// flag as false
isLocationAvailable = false;
return null;
}
public String getCountryCode() {
getLocation();
if (isLocationAvailable) {
Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
// Get the current location from the input parameter list
// Create a list to contain the result address
List<Address> addresses = null;
try {
/*
* Return 1 address.
*/
mLatitude = getLatitude();
mLongitude = getLongitude();
addresses = geocoder.getFromLocation(mLatitude, mLongitude, 1);
} catch (IOException e1) {
e1.printStackTrace();
Log.e("returning", "tm");
//TelephonyManager tm = (TelephonyManager)mContext.getSystemService(mContext.TELEPHONY_SERVICE);
//return tm.getNetworkCountryIso();
} catch (IllegalArgumentException e2) {
// Error message to post in the log
String errorString = "Illegal arguments "
+ Double.toString(mLatitude) + " , "
+ Double.toString(mLongitude)
+ " passed to address service";
e2.printStackTrace();
return errorString;
}
// If the reverse geocode returned an address
if (addresses != null && addresses.size() > 0) {
// Get the first address
Address address = addresses.get(0);
/*
* Format the first line of address (if available), city, and
* country name.
*/
// Return the text
Log.e("returning", address.getCountryCode());
String countrycode;
if (address.getCountryCode() == null) {
countrycode = "null";
} else {
countrycode = address.getCountryCode();
}
return countrycode;
} else {
return "null";
}
} else {
//String locale = getResources().getConfiguration().locale.getCountry();
Log.e("returning", "wifi");
getJSON();
Log.e("ELSE", wifiCode);
return wifiCode;
}
}

How to get country name in android?

Hi I am working with android.I had created a GPS app for getting the current location.Now How can I get the country name from the latitude and longitude value ? is it possible ? please help me and thanks :)
here is my code I used
public class AndroidGPSTrackingActivity extends Activity {
Button btnShowLocation;
// GPSTracker class
GPSTracker gps;
String countryCode,countryName;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
// show location button click event
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// create class object
gps = new GPSTracker(AndroidGPSTrackingActivity.this);
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Log.i("location", " "+latitude+" "+longitude);
// \n is for new line
try
{Geocoder gcd = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> addresses = gcd.getFromLocation(latitude,longitude, 1);
if (addresses.size() > 0)
Toast.makeText(getApplicationContext(), "name "+addresses.get(0).getLocality(),Toast.LENGTH_SHORT).show();
//System.out.println(addresses.get(0).getLocality());
}
catch (IOException e) {
e.printStackTrace();
}
//Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude+countryName +" "+countryCode, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
});
}
}
String country_name = null;
LocationManager lm = (LocationManager)getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
Geocoder geocoder = new Geocoder(getApplicationContext());
for(String provider: lm.getAllProviders()) {
#SuppressWarnings("ResourceType") Location location = lm.getLastKnownLocation(provider);
if(location!=null) {
try {
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if(addresses != null && addresses.size() > 0) {
country_name = addresses.get(0).getCountryName();
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Toast.makeText(getApplicationContext(), country_name, Toast.LENGTH_LONG).show();
Finally I got the solution, without lat and long value, i got country name.
String country = getApplicationContext().getResources().getConfiguration().locale.getDisplayCountry();
.
Use this:
Geocoder myLocation = new Geocoder(AppContext);
try
{
myList = myLocation.getFromLocation(latitude, longitude, 1);
}
catch (Exception e)
{
e.printStackTrace();
}
if(myList != null)
{
try
{
String country = myList.get(0).getCountryName();}
You can Get Country name from below mentioned json. Just pass your lat-long in address. And look for "long_name" which have "country,political" in "types" array.
i.e. http://maps.googleapis.com/maps/api/geocode/json?address=23.022505,72.5713621&sensor=false
From a Geocoder object, you can call the getFromLocation(double, double, int) method. It will return a list of Address objects that have a method getLocality().
import android.location.Address;
import android.location.Geocoder;
Geocoder gcd = new Geocoder(this, Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(1.2, 2.2256, 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
List<Address> addresses=null;
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(loc.latitude, loc.longitude, 1);
System.out.println("add in string "+addresses.toArray().toString());
String countryName = addresses.get(0).getCountryName();
String countryCode = addresses.get(0).getCountryCode();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Geocoder not working

I have an Android application where I need to get address from lat/long. I have used the following code base:
Geocoder geoCoder = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> address = null;
if (geoCoder != null){
try {
address= geoCoder.getFromLocation(51.50, -0.12, 1);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (address.size()> 0){
String postCode = address.get(0).getPostalCode();
System.out.println(postCode);
}
}
I have also added the following in my manifest file
uses-permission android:name="android.permission.INTERNET"
uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
but every time I execute this block address.size() remains "0", I have tried with different coordinates also; nothing changed at all. I'm doing all this from eclipse.
Try this:
private class ReverseGeocodingTask extends AsyncTask<Location, Void, Void> {
Context mContext;
public ReverseGeocodingTask(Context context) {
super();
mContext = context;
}
#Override
protected Void doInBackground(Location... params) {
Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
Location loc = params[0];
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
// Format the first line of address (if available), city, and
// country name.
final String addressText = String.format(
"%s, %s, %s",
address.getMaxAddressLineIndex() > 0 ? address
.getAddressLine(0) : "", address.getLocality(),
address.getCountryName());
// Update address field on UI.
mHandler.post(new Runnable() {
public void run() {
Toast.makeText(getBaseContext(),
addressText.toString(), Toast.LENGTH_SHORT)
.show();
}
});
}
return null;
}
}

cannot get place from google map using location

I try to get place(ex: locality, country, postal code) form google map using
latitude and longitude. The following is my code that got null data:
Edit:
public void onLocationChanged(Location location) {
geocoder = new Geocoder(this, Locale.getDefault());
if (location != null) {
try {
addresses = geocoder.getFromLocation(location.getLatitude()/1E6,
location.getLongitude()/1E6, 1);
if (addresses.size() > 0) {
resultAddress = addresses.get(0);
locality = resultAddress.getLocality();
sublocality = resultAddress.getSubLocality();
postalcode = resultAddress.getPostalCode();
country = resultAddress.getCountryName();
adminarea = resultAddress.getSubAdminArea();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I tried to assign latitude and longitude manually, but got nothing.
Any one can correct my mistakes ? Thank you
I think the problem is on the parameters of the method. I guess that location is a GeoPoint In that case, instead of
addresses = geocoder.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
try this:
addresses = geocoder.getFromLocation(location.getLatitude()/1E6,
location.getLongitude()/1E6, 1);
because the coordinates in a geopoint are represented in microdegrees
Edit
I copied your code and tried it. Assuming your "location" object is a GeoPoint, the code that works is as follows:
GeoPoint location = new GeoPoint(lat, lon);
if (location != null) {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(location.getLatitudeE6()/1E6,
location.getLongitudeE6()/1E6, 1);
if (addresses.size() > 0) {
Address resultAddress = addresses.get(0);
String locality = resultAddress.getLocality();
String sublocality = resultAddress.getSubLocality();
String postalcode = resultAddress.getPostalCode();
String country = resultAddress.getCountryName();
String adminarea = resultAddress.getSubAdminArea();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
however, if you are testing it on the emulator, be sure you have internet connection. Otherwise, the method "getFromLocation" cannot find out the address and won't display anything. If you don't have any error in the logcat and the problem is only that nothing is displayed, that is the problem: no network.
Do you have the <uses-permission android:name="android.permission.INTERNET" /> in manifest.xml?

Categories

Resources