Android Google Maps stop unfortunately on other device - android

Why my GoogleMaps is making my app stop unfortunately when I run it in another devices? Here is my code:
mapFragment.getMapAsync(this);
prefs = getSharedPreferences(AppConstants.LOGIN_PREFS,
Context.MODE_PRIVATE);
}
public void onMapSearch(View view) {
EditText locationSearch = (EditText) findViewById(R.id.editText);
String location = locationSearch.getText().toString();
List<android.location.Address> addressList = null;
if (location != null || !location.equals("")) {
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title("Click here"));
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
String frst = address.getLocality();
Double lat=address.getLatitude();
Double longi=address.getLongitude();
SharedPreferences.Editor editor = getSharedPreferences(AppConstants.VERIFICATION, MODE_PRIVATE).edit();
editor.putString(AppConstants.CITYNAME, frst);
editor.putString(AppConstants.LAT,""+lat);
editor.putString(AppConstants.LONG,""+longi);
editor.commit();
Intent intent = new Intent(MapsActivity.this, MainActivity.class);
startActivity(intent);
}
});
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
#Override
protected void onResume() {
super.onResume();
// create class object
final GPSTracker gps = new GPSTracker(MapsActivity.this);
// check if GPS enabled
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
if (latitude != 0.0 && longitude != 0.0) {
if (Utils.isNetworkAvailable(MapsActivity.this))
sendGetAddressRequest(latitude, longitude);
else
Toast.makeText(MapsActivity.this, "need_network", Toast.LENGTH_LONG).show();
} else {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
if (latitude != 0.0 && longitude != 0.0) {
if (Utils.isNetworkAvailable(MapsActivity.this)) {
sendGetAddressRequest(latitude, longitude);
} else
Toast.makeText(MapsActivity.this, "need_network", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MapsActivity.this, "couldn't get your current location enter manually", Toast.LENGTH_LONG).show();
}
}
}, 10000);
}
} else {
}
}
private void sendGetAddressRequest(double latitude, double longitude) {
// lat.setText("latitude" + latitude);
if (Utils.isNetworkAvailable(MapsActivity.this)) {
getAddressAsync = new GetAddress(latitude, longitude);
getAddressAsync.execute();
} else {
Toast.makeText(MapsActivity.this, "need_network", Toast.LENGTH_LONG).show();
}
}
private class GetAddress extends AsyncTask<String, String, String> {
double latitude, longitude;
public GetAddress(double latitude, double longitude) {
this.latitude = latitude;
this.longitude = longitude;
}
#Override
protected String doInBackground(String... params) {
String result = null;
HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?address=" + latitude + "," + longitude + "&ka&sensor=false");
// Log.d(TAG, "CURRENT ADDRESS API : " + "http://maps.google.com/maps/api/geocode/json?address=" + latitude + "," + longitude + "&ka&sensor=false");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
} catch (JSONException e) {
e.printStackTrace();
}
result = jsonObject.toString();
// Log.d(TAG, "Address : " + result);
return result;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// progressBar.setVisibility(View.VISIBLE);
// progressBar.setClickable(true);
// currentLocation.setVisibility(View.GONE);
}
#Override
protected void onPostExecute(String s) {
if (s != null) {
try {
JSONObject result = new JSONObject(s);
if (result.has("results")) {
JSONArray array = result.getJSONArray("results");
if (array.length() > 0) {
JSONObject place = array.getJSONObject(0);
JSONArray components = place.getJSONArray("address_components");
for (int i = 0; i < components.length(); i++) {
JSONObject component = components.getJSONObject(i);
JSONArray types = component.getJSONArray("types");
for (int j = 0; j < types.length(); j++) {
if (types.getString(j).equals("locality")) {
cityName = component.getString("long_name");
} else if (types.getString(j).equals("premise")) {
plot = component.getString("long_name");
} else if (types.getString(j).equals("sublocality_level_1")) {
area = component.getString("long_name");
} else if (types.getString(j).equals("administrative_area_level_1")) {
state = component.getString("long_name");
} else if (types.getString(j).equals("postal_code")) {
postalCode = component.getString("long_name");
} else if (types.getString(j).equals("country")) {
country = component.getString("long_name");
}
}
}
formattedAddress = place.getString("formatted_address");
onMapReady(mMap);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
// Log.d(TAG, "Locality : " + cityName + ", Area : " + area + ", State : " + state + ", PostalCode : " + postalCode + ", Country : " + country);
}
}
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng latlng = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(latlng).draggable(true).title("Current Location"));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(30));
// mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
// #Override
// public void onInfoWindowClick(Marker marker) {
//
// Intent intent = new Intent(MapsActivity.this, MainActivity.class);
// intent.putExtra("City",cityName);
// intent.putExtra("Area",area);
// intent.putExtra("State",state);
// intent.putExtra("PostalCode",postalCode);
// intent.putExtra("Country",country);
// intent.putExtra("Plot",plot);
// startActivity(intent);
//
// }
// });
}
}
When I run my app on other devices, it crashes sometimes but when I run it on my phone, it works fine. On most of devices, I got a crash.
I don't know where it is throwing an exception.
Suggest me something guys, please, I'm stuck in this from a very long time. I want to fix it on every phone.

Related

how to convert longitude and latitude into text format to show street address?

I am developing an app,In this I'm using google map to show users current location.
Following code I am using but it doesn't give the result of street address only shows the current location in map and shows longitude and latitude.How do I show the current street address in text field from current longitude and latitude?
//java
public class LocationActivity extends Activity {
private TextView locationText;
private TextView addressText, textview;
private GoogleMap map;
String mob_no;
private boolean loggedIn = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
locationText = (TextView) findViewById(R.id.location);
addressText = (TextView) findViewById(R.id.address);
// textview=(TextView)findViewById(R.id.textView_euser);
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);
mob_no = sharedPreferences.getString(Config.PHONE_SHARED_PREF, "Not Available");
// textview.setText(String.valueOf(mob_no));
//replace GOOGLE MAP fragment in this Activity
replaceMapFragment();
}
private void replaceMapFragment() {
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
// Enable Zoom
map.getUiSettings().setZoomGesturesEnabled(true);
//set Map TYPE
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//enable Current location Button
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
map.setMyLocationEnabled(true);
//set "listener" for changing my location
map.setOnMyLocationChangeListener(myLocationChangeListener());
}
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener() {
return new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Marker marker;
marker = map.addMarker(new MarkerOptions().position(loc));
map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
locationText.setText("You are at [" + longitude + " ; " + latitude + " ]");
//get current address by invoke an AsyncTask object
new GetAddressTask(LocationActivity.this).execute(String.valueOf(latitude), String.valueOf(longitude));
// getCompleteAddressString(longitude,latitude);
}
};
}
public void callBackDataFromAsyncTask(String address) {
addressText.setText(address);
}
/* #SuppressLint("LongLogTag")
private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
String strAdd = "";
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if (addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:");
for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
strAdd = strReturnedAddress.toString();
addressText.setText(strAdd);
Log.w("My Current loction address", "" + strReturnedAddress.toString());
} else {
Log.w("My Current loction address", "No Address returned!");
}
} catch (Exception e) {
e.printStackTrace();
Log.w("My Current loction address", "Canont get Address!");
}
return strAdd;
} */
}
//getaddress
public class GetAddressTask extends AsyncTask<String, Void, String> {
private LocationActivity activity;
public GetAddressTask(LocationActivity activity) {
super();
this.activity = activity;
}
#Override
protected String doInBackground(String... params) {
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(activity, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(Double.parseDouble(params[0]), Double.parseDouble(params[1]), 1);
//get current Street name
String address = addresses.get(0).getAddressLine(0);
//get current province/City
String province = addresses.get(0).getAdminArea();
//get country
String country = addresses.get(0).getCountryName();
//get postal code
String postalCode = addresses.get(0).getPostalCode();
//get place Name
String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL
return "Street: " + address + "\n" + "City/Province: " + province + "\nCountry: " + country
+ "\nPostal CODE: " + postalCode + "\n" + "Place Name: " + knownName;
} catch (IOException ex) {
ex.printStackTrace();
return "IOE EXCEPTION";
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
return "IllegalArgument Exception";
}
}
/**
* When the task finishes, onPostExecute() call back data to Activity UI and displays the address.
* #param address
*/
#Override
protected void onPostExecute(String address) {
// Call back Data and Display the current address in the UI
activity.callBackDataFromAsyncTask(address);
}
}
You can use Double.toString() to convert a double to a String. Alternatively, you can use +:
"" + latitude
If you need more control over the output, such as the number of decimal places to display, you can use String.format().
public static void getAddressFromLocation(final double latitude, final double longitude,
final Context context, final Handler handler) {
Thread thread = new Thread() {
#Override
public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
try {
List<Address> addressList = geocoder.getFromLocation(
latitude, longitude, 1);
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
StringBuilder sb = new StringBuilder();
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());
result = sb.toString();
}
} catch (IOException e) {
Log.e(TAG, "Unable connect to Geocoder", e);
} finally {
Message message = Message.obtain();
message.setTarget(handler);
if (result != null) {
message.what = 1;
Bundle bundle = new Bundle();
result = "Latitude: " + latitude + " Longitude: " + longitude +
"\n\nAddress:\n" + result;
bundle.putString("address", result);
message.setData(bundle);
} else {
message.what = 1;
Bundle bundle = new Bundle();
result = "Latitude: " + latitude + " Longitude: " + longitude +
"\n Unable to get address for this lat-long.";
bundle.putString("address", result);
message.setData(bundle);
}
message.sendToTarget();
}
}
};
thread.start();
}
more info please check below link:-
http://javapapers.com/android/android-get-address-with-street-name-city-for-location-with-geocoding/
its helps to you

How to get address from latitude and longitude android google map v2 [duplicate]

This question already has answers here:
get latitude and longitude with geocoder and android Google Maps API v2
(5 answers)
Closed 7 years ago.
I am trying to get an address from latitude and longitude in Android Google Maps v2, but it errors.
Here is my code:
case PLACES_DETAILS :
final HashMap<String, String> hm = result.get(0);
final double latitude = Double.parseDouble(hm.get("lat"));
final double longitude = Double.parseDouble(hm.get("lng"));
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googleMap = fm.getMap();
final LatLng point = new LatLng(latitude, longitude);
CameraUpdate cameraPosition = CameraUpdateFactory.newLatLngZoom(point, 10);
CameraUpdate cameraZoom = CameraUpdateFactory.zoomBy(5);
googleMap.moveCamera(cameraPosition);
googleMap.animateCamera(cameraZoom);
googleMap.getCameraPosition();
//Log.e("Lat", String.valueOf(googleMap.getCameraPosition().target.latitude));
//Log.e("Long", String.valueOf(googleMap.getCameraPosition().target.latitude));
//googleMap.setOnMyLocationChangeListener(myLocationChangeListener);
googleMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition cameraPosition) {
Log.e("Lat", String.valueOf(googleMap.getCameraPosition().target.latitude));
Log.e("Long", String.valueOf(googleMap.getCameraPosition().target.longitude));
}
});
Use the following code snippet:
try {
Geocoder geo = new Geocoder(youractivityclassname.this.getApplicationContext(), Locale.getDefault());
List<Address> addresses = geo.getFromLocation(latitude, longitude, 1);
if (addresses.isEmpty()) {
yourtextfieldname.setText("Waiting for Location");
}
else {
if (addresses.size() > 0) {
yourtextfieldname.setText(addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() +", " + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryName());
//Toast.makeText(getApplicationContext(), "Address:- " + addresses.get(0).getFeatureName() + addresses.get(0).getAdminArea() + addresses.get(0).getLocality(), Toast.LENGTH_LONG).show();
}
}
}
catch (Exception e) {
e.printStackTrace(); // getFromLocation() may sometimes fail
}
reference :
https://mobiforge.com/design-development/using-google-maps-android
This should give you the address for your lat long
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(mContext, Locale.getDefault());
try {
String sPlace;
addresses = geocoder.getFromLocation(mLat, mLong, 1);
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getAddressLine(1);
String country = addresses.get(0).getAddressLine(2);
String[] splitAddress = address.split(",");
sPlace = splitAddress[0] + "\n";
if(city != null && !city.isEmpty()) {
String[] splitCity = city.split(",");
sPlace += splitCity[0];
}
} catch (IOException e) {
e.printStackTrace();
}
I am giving you my code, i use this code,2 months ago.. I didn't able to test this code right now, but it worked that time. may u need to modify some lines.
use this function
public void getAddressByLatLong(){
latitude = bundle.getDouble("Lat");
longitude = bundle.getDouble("Long");
LatLng pos = new LatLng(latitude, longitude);
try {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager()
.findFragmentById(R.id.map)).getMap();
}
googleMap.setMapType(googleMap.MAP_TYPE_HYBRID);
LocationManager location_manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener listner = new MyLocationListner();
location_manager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 3000, 5000, listner);
} catch (Exception e) {
e.printStackTrace();
}
}
Create a class
public class MyLocationListner implements LocationListener {
#SuppressLint("NewApi")
#SuppressWarnings("static-access")
#Override
public void onLocationChanged(Location arg0) {
Toast.makeText(getApplicationContext(),
"In on Location Changed", Toast.LENGTH_SHORT).show();
// TODO Auto-generated method stub
getLatitude = "" + arg0.getLatitude();
getLongitude = "" + arg0.getLongitude();
// lati.setText(getLatitude + "," + getLongitude);
latitude = arg0.getLatitude();
longitude = arg0.getLongitude();
try {
geocoder = new Geocoder(DisplayActivity.this, Locale.ENGLISH);
addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (geocoder.isPresent()) {
Toast.makeText(getApplicationContext(), "geocoder present",
Toast.LENGTH_SHORT).show();
Address returnAddress = addresses.get(0);
String localityString = returnAddress.getLocality();
String city = returnAddress.getCountryName();
String region_code = returnAddress.getCountryCode();
String zipcode = returnAddress.getPostalCode();
str = new StringBuilder();
str.append(localityString + " ");
str.append(city + " ");
str.append(region_code + " ");
str.append(zipcode + " ");
// Add = str.toString();
// longi.setText(str);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude)).zoom(2)
.build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
MarkerOptions marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title(
str.toString());
marker.icon(BitmapDescriptorFactory
.fromResource(R.drawable.mario));
googleMap.addMarker(marker);
Toast.makeText(getApplicationContext(), str,
Toast.LENGTH_SHORT).show();
} else
Toast.makeText(getApplicationContext(),
"geocoder not present", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Exception",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onProviderDisabled(String arg0) {
}
#Override
public void onProviderEnabled(String arg0) {
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
}

How to get address from latitude and longitude in Android?

I am building an android application where I am using TouchableWrapper class for getting latitude & longitude.When a user removes the finger, the camera center position latitude and longitude are parsed and shown in a toast.
Now all I need is the address at that latitude and longitude.
Here is code that I am using to get latitude and longitude:
public class MainActivity extends FragmentActivity implements TouchActionDown, TouchActionUp {
CameraPosition mDownCameraPosition;
CameraPosition mUpCameraPosition;
ImageView submitbtn,mappoint;
String addressfixed,completed;
EditText whitebord;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maintut);
// get data views
mappoint = (ImageView) findViewById(R.id.mappoint);
whitebord = (EditText) findViewById(R.id.searchmapedit);
mappoint.setImageResource(R.drawable.point);
submitbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
onBackPressed();
}
});
getMap().getMap().setMyLocationEnabled(true);
getMap().getMap().setOnMapLoadedCallback(
new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
Location myLocation = getMap().getMap().getMyLocation();
LatLng myLatLng = new LatLng(myLocation.getLatitude(),
myLocation.getLongitude());
CameraPosition myPosition = new CameraPosition.Builder()
.target(myLatLng).zoom(17).bearing(90).tilt(30)
.build();
getMap().getMap().animateCamera(
CameraUpdateFactory
.newCameraPosition(myPosition));
}
});
}
#Override
protected void onResume() {
super.onResume();
// check google play services
int isAvailable = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (isAvailable != ConnectionResult.SUCCESS) {
GooglePlayServicesUtil.getErrorDialog(isAvailable, this, 1).show();
}
}
#Override
public void onTouchDown(MotionEvent event) {
mDownCameraPosition = getMap().getMap().getCameraPosition();
}
#Override
public void onTouchUp(MotionEvent event) {
mUpCameraPosition = getMap().getMap().getCameraPosition();
getMap().getMap().clear();// to remove previous marker
MarkerOptions options = new MarkerOptions()
.title("This is your selected place to host game")
.position(
new LatLng(mUpCameraPosition.target.latitude,
mUpCameraPosition.target.longitude));
new GetAddressTask(getApplicationContext()).execute();
}
private SupportMapFragment getMap() {
return ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map));
}
public class GetAddressTask extends AsyncTask<android.location.Location, Void, String> {
public GetAddressTask (Context context) {
super();
mContext = context;
}
#Override
protected String doInBackground (android.location.Location... params) {
Geocoder geocoder =
new Geocoder(mContext, Locale.getDefault());
android.location.Location location = params[0];
Location markerLocation = getMap().getMap().getMyLocation();
List<Address> addresses = null;
try {
if (mByMap && markerLocation != null) {
addresses = geocoder.getFromLocation(markerLocation.getLatitude(),
markerLocation.getLongitude(), 1);
} else if (!mByMap && location != null) {
addresses = geocoder.getFromLocation(mUpCameraPosition.target.latitude,
mUpCameraPosition.target.longitude, 1);
}
} catch (IOException exception) {
Log.e("ComplaintLocation",
"IO Exception in getFromLocation()", exception);
// handler.post(new Runnable() {
//
// #Override
// public void run() {
// Toast.makeText(mContext,
// mContext.getString("Updating your location failed"),
// Toast.LENGTH_SHORT).show();
// }
// });
return ("IO Exception trying to get address");
} catch (IllegalArgumentException exception) {
String errorString = "Illegal arguments " +
Double.toString(location.getLatitude()) + " , " +
Double.toString(location.getLongitude()) + " passed to address service";
Log.e("LocationSampleActivity", errorString, exception);
return errorString;
}
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
if (address.getMaxAddressLineIndex() > 0) {
return String.format(
"%s/%s/%s/%s/%s/%s",
address.getLatitude(), // 0
address.getLongitude(), // 1
address.getThoroughfare(), // 2
address.getSubThoroughfare(), //3
address.getPostalCode(), // 4
address.getLocality()); // 5
} else {
return String.format(
"%s/%s/%s/%s",
address.getLatitude(), // 0
address.getLongitude(), // 1
address.getPostalCode(), // 2
address.getLocality()); // 3
}
} else return "No address found";
}
// Format address string after lookup
#Override
protected void onPostExecute (String address) {
String[] addressFields = TextUtils.split(address, "/");
Log.d("ADDRESS ARRAY", Arrays.toString(addressFields));
// Log.d("LOCATION", "Using " + mProvider);
// Workaround: doInBackground can only return Strings instead of, for example, an
// Address instance or a String[] directly. To be able to use TextUtils.isEmpty()
// on fields returned by this method, set each String that currently reads "null" to
// a null reference
for (int fieldcnt = 0; fieldcnt < addressFields.length; ++fieldcnt) {
if (addressFields[fieldcnt].equals("null"))
addressFields[fieldcnt] = null;
}
String mStreet,mHouseNumber,mLatitude,mLongtitude,mPostalCode,mCity;
switch (addressFields.length) {
case 4:
mStreet = null;
mHouseNumber = null;
mLatitude = addressFields[0];
mLongtitude = addressFields[1];
mPostalCode = addressFields[2];
mCity = addressFields[3];
break;
case 6:
mLatitude = addressFields[0];
mLongtitude = addressFields[1];
mStreet = addressFields[2];
mHouseNumber = addressFields[3];
mPostalCode = addressFields[4];
mCity = addressFields[5];
break;
default:
mLatitude = null;
mLongtitude = null;
mStreet = null;
mHouseNumber = null;
mPostalCode = null;
mCity = null;
break;
}
Toast.makeText(getApplicationContext(), mStreet,
Toast.LENGTH_LONG).show();
}
}
private boolean mByMap;
// Lookup address via reverse geolocation
public void lookUpAddress (boolean byMap) {
mByMap = byMap;
if (Geocoder.isPresent()) {
// (new GetAddressTask(mContext)).execute(mCurrentBestLocation);
}
}
private SupportMapFragment getMap() {
return ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map));
}
}
Any help would be greatly appreciated.
You can get address by GeoCoder Object
note that you will receive a list of suggested addresses.
Here in the example I take the first one
Geocoder geocoder;
List<Address> yourAddresses;
geocoder = new Geocoder(this, Locale.getDefault());
yourAddresses= geocoder.getFromLocation(yourLatitude, yourLongitude, 1);
if (yourAddress.size() > 0)
{
String yourAddress = yourAddresses.get(0).getAddressLine(0);
String yourCity = yourAddresses.get(0).getAddressLine(1);
String yourCountry = yourAddresses.get(0).getAddressLine(2);
}
You can use GeoCoder for the purpose of finding a Location Address by providing latitude and longtitude as described in the Android Developer Guidelines: Displaying a Location Address
Because I had trouble finding it when I was searching for it recently: You can get the street by using Address's getThoroughfare (and getSubThoroughfare) getter methods.
Create a new class GeoLocation, copy the following into it:
package com.stackoverflow.hitesh.geocoder;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
public class GeoLocation {
private Context mContext;
private String mLatitude;
private String mLongtitude;
private String mStreet;
private String mHouseNumber;
private String mPostalCode;
private String mCity;
private Location mMarkerLocation;
public GeoLocation (Context context) {
mContext = context;
}
public String getStreet () {
return mStreet;
}
public String getHouseNumber () {
return mHouseNumber;
}
public String getPostalCode () {
return mPostalCode;
}
public String getCity () {
return mCity;
}
public String getLatitude () {
return mLatitude;
}
public String getLongtitude () {
return mLongtitude;
}
// Lookup address via reverse geolocation
// Call this one
public void lookUpAddress (Location markerLocation) {
mMarkerLocation = markerLocation;
if (Geocoder.isPresent()) {
(new GetAddressTask(mContext)).execute();
}
}
public class GetAddressTask extends AsyncTask<android.location.Location, Void, String> {
public GetAddressTask (Context context) {
super();
mContext = context;
}
#Override
protected String doInBackground (android.location.Location... params) {
Geocoder geocoder =
new Geocoder(mContext, Locale.getDefault());
android.location.Location location = params[0];
List<Address> addresses = null;
try {
if (mMarkerLocation != null) {
addresses = geocoder.getFromLocation(mMarkerLocation.getLatitude(),
mMarkerLocation.getLongitude(), 1);
}
} catch (IOException exception) {
Log.e("ComplaintLocation",
"IO Exception in getFromLocation()", exception);
return ("IO Exception trying to get address");
} catch (IllegalArgumentException exception) {
String errorString = "Illegal arguments " +
Double.toString(location.getLatitude()) + " , " +
Double.toString(location.getLongitude()) + " passed to address service";
Log.e("LocationSampleActivity", errorString, exception);
return errorString;
}
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
if (address.getMaxAddressLineIndex() > 0) {
return String.format(
"%s/%s/%s/%s/%s/%s",
address.getLatitude(), // 0
address.getLongitude(), // 1
address.getThoroughfare(), // 2
address.getSubThoroughfare(), //3
address.getPostalCode(), // 4
address.getLocality()); // 5
} else {
return String.format(
"%s/%s/%s/%s",
address.getLatitude(), // 0
address.getLongitude(), // 1
address.getPostalCode(), // 2
address.getLocality()); // 3
}
} else return "No address found";
}
// Format address string after lookup
#Override
protected void onPostExecute (String address) {
String[] addressFields = TextUtils.split(address, "/");
Log.d("ADDRESS ARRAY", Arrays.toString(addressFields));
// Workaround: doInBackground can only return Strings instead of, for example, an
// Address instance or a String[] directly. To be able to use TextUtils.isEmpty()
// on fields returned by this method, set each String that currently reads "null" to
// a null reference
for (int fieldcnt = 0; fieldcnt < addressFields.length; ++fieldcnt) {
if (addressFields[fieldcnt].equals("null"))
addressFields[fieldcnt] = null;
}
switch (addressFields.length) {
case 4:
mStreet = null;
mHouseNumber = null;
mLatitude = addressFields[0];
mLongtitude = addressFields[1];
mPostalCode = addressFields[2];
mCity = addressFields[3];
break;
case 6:
mLatitude = addressFields[0];
mLongtitude = addressFields[1];
mStreet = addressFields[2];
mHouseNumber = addressFields[3];
mPostalCode = addressFields[4];
mCity = addressFields[5];
break;
default:
mLatitude = null;
mLongtitude = null;
mStreet = null;
mHouseNumber = null;
mPostalCode = null;
mCity = null;
break;
}
Log.d("GeoLocation Street", mStreet);
Log.d("GeoLocation No.", mHouseNumber);
Log.d("GeoLocation Postalcode", mPostalCode);
Log.d("GeoLocation Locality", mCity);
Log.d("GeoLocation Lat/Lng", "[" + mLatitude + ", " + mLongtitude + "]");
}
}
}
You then instantiate it using
GeoLocation geoLocation = new GeoLocation(getActivity()); // or (this) if called from an activity and not from a fragment
mGeoLocation.lookUpAddress(LOCATION_FROM_MAP);
Of course, you have to replace LOCATION_FROM_MAP with the Location object you get from your map.
use this code for converting latitude and longitute to address on camera change
#Override
public void onCameraChange(CameraPosition cameraPosition)
{
mGoogleMap.setOnMapLoadedCallback(this);
}
#Override
public void onMapLoaded()
{
LatLng position = mGoogleMap.getCameraPosition().target;
double Lat = position.latitude;
double Long = position.longitude;
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try
{
addresses = geocoder.getFromLocation(Lat, Long, 1);
if (addresses != null && addresses.size() > 0)
{
String address = addresses.get(0).getAddressLine(0);
String address11 = addresses.get(0).getAddressLine(1);
String city = addresses.get(0).getLocality();
}
}
catch (IOException e) {
}
}
and call onCameraChangeListener in onMapReady after map load
mGoogleMap.setOnCameraChangeListener(this);

Location manager in android get wrong results

I am writing android code to get current location and convert lat,long to address but I am getting wrong results,
the problem is here:
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
Log.d("msgh","msgh");
} else {
System.out.println("location not available");
Log.d("msg","msg");
}
the code enters the else statement always
Try this one it works
private static final AndroidHttpClient ANDROID_HTTP_CLIENT = AndroidHttpClient.newInstance(GeoCoderHelper.class.getName());
private boolean running = false;
public interface CityListener {
public void cityNameListener(String s);
}
public void fetchCityName(final Context contex, final Location location,final CityListener listener)
{
if (running)
return;
new AsyncTask<Void, Void, String>()
{
protected void onPreExecute()
{
running = true;
};
#Override
protected String doInBackground(Void... params)
{
String cityName = null;
if (Geocoder.isPresent())
{
try
{
Geocoder geocoder = new Geocoder(contex, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (addresses.size() > 0)
{
cityName = addresses.get(0).getLocality();
}
}
catch (Exception ignored)
{
// after a while, Geocoder start to trhow "Service not availalbe" exception. really weird since it was working before (same device, same Android version etc..
}
}
if (cityName != null) // i.e., Geocoder succeed
{
return cityName;
}
else // i.e., Geocoder failed
{
return fetchCityNameUsingGoogleMap();
}
}
// Geocoder failed :-(
// Our B Plan : Google Map
private String fetchCityNameUsingGoogleMap()
{
String googleMapUrl = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + location.getLatitude() + ","
+ location.getLongitude() + "&sensor=false&language=fr";
try
{
JSONObject googleMapResponse = new JSONObject(ANDROID_HTTP_CLIENT.execute(new HttpGet(googleMapUrl),
new BasicResponseHandler()));
// many nested loops.. not great -> use expression instead
// loop among all results
JSONArray results = (JSONArray) googleMapResponse.get("results");
for (int i = 0; i < results.length(); i++)
{
// loop among all addresses within this result
JSONObject result = results.getJSONObject(i);
if (result.has("address_components"))
{
JSONArray addressComponents = result.getJSONArray("address_components");
// loop among all address component to find a 'locality' or 'sublocality'
for (int j = 0; j < addressComponents.length(); j++)
{
JSONObject addressComponent = addressComponents.getJSONObject(j);
if (result.has("types"))
{
JSONArray types = addressComponent.getJSONArray("types");
// search for locality and sublocality
String cityName = null;
String countyName = null ;
for (int k = 0; k < types.length(); k++)
{
if ("locality".equals(types.getString(k)) && cityName == null)
{
if (addressComponent.has("long_name"))
{
cityName = addressComponent.getString("long_name");
}
else if (addressComponent.has("short_name"))
{
cityName = addressComponent.getString("short_name");
}
}
if ("sublocality".equals(types.getString(k)))
{
if (addressComponent.has("long_name"))
{
cityName = addressComponent.getString("long_name");
}
else if (addressComponent.has("short_name"))
{
cityName = addressComponent.getString("short_name");
}
}
}
if (cityName != null)
{
return cityName;
}
}
}
}
}
}
catch (Exception ignored)
{
ignored.printStackTrace();
}
return null;
}
protected void onPostExecute(String cityName)
{
running = false;
if (cityName != null)
{
// Do something with cityName
Log.i("GeocoderHelper", cityName);
listener.cityNameListener(cityName);
}
};
}.execute();
}
and you can call like this
new GeoCoderHelper().fetchCityName(this,location,new GeoCoderHelper.CityListener() {
#Override
public void cityNameListener(String s) {
addressCityTextView.setText(s);
}
});

Geocoder not working in android 2.3.3 and android 3.0

public class LocateActivity extends MapActivity {
MapView mapView = null;
Geocoder geocoder = null;
Drawable drawable = null;
Geocoder gc = null;
final CountDownLatch signal = new CountDownLatch(1);
String status;
double lat;
double lng;
public ArrayAdapter<String> adapter;
public AutoCompleteTextView filltt;
public static String KEY_REFERENCE = "reference"; // id of the place
public static String KEY_NAME = "name"; // name of the place
public static String KEY_VICINITY = "vicinity"; //
ProgressDialog pDialog;
PlacesList nearPlaces;
List<Overlay> mapOverlays;
AddItemizedOverlay itemizedOverlay;
GeoPoint geoPoint;
// Map controllers
MapController mc;
double latitude;
double longitude;
OverlayItem overlayitem;
Drawable drawable_user;
Drawable drawablee;
String locnm;
GPSTracker gps;
GooglePlaces googlePlaces;
ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String,String>>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
System.out.println("My locale::"+Locale.getDefault().getDisplayLanguage());
filltt = (AutoCompleteTextView)findViewById(id.autoCompleteTextView1);
mapView = (MapView) findViewById(R.id.geoMap);
mapView.setBuiltInZoomControls(true);
mapView.setClickable(true);
mapOverlays = mapView.getOverlays();
gc = new Geocoder(this);
drawable = this.getResources().getDrawable(R.drawable.pon);
adapter = new ArrayAdapter<String>(this,R.layout.item_list);
adapter.setNotifyOnChange(true);
filltt.setAdapter(adapter);
filltt.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (count%3 == 1) {
adapter.clear();
GetPlaces task = new GetPlaces();
//now pass the argument in the textview to the task
task.execute(filltt.getText().toString());
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable s) {
}
});
// map starting point
int lat = (int) (51.678383 * 1000000);
int lng = (int) (19.334822 * 1000000);
GeoPoint pt = new GeoPoint(lat, lng);
mapView.getController().setZoom(18);
mapView.getController().setCenter(pt);
final String lattt="23.0666";
final String loggg="72.6666";
Button geoBtn = (Button) findViewById(R.id.geocodeBtn);
// geoBtn.setText(Html.fromHtml("<b>Year:</b>2012,<b>Franch</b>"));
geocoder = new Geocoder(this);
geoBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
locnm = filltt.getText().toString();
if(locnm.length()==0){
Toast.makeText(LocateActivity.this, "Enter Location", Toast.LENGTH_LONG).show();
}
else
// EditText locale = (EditText) findViewById(R.id.location);
{
new LoadPlaces().execute();
String locationName = filltt.getText().toString();
Toast.makeText(LocateActivity.this, locationName, Toast.LENGTH_LONG).show();
System.out.println("location: "+locationName);
List<Address> addressList = geocoder.getFromLocationName(
locationName, 5);
System.out.println("first val: " + addressList.get(0));
System.out.println("Total Result: " + addressList.size());
if (addressList != null && addressList.size() > 0) {
int lat = (int) (addressList.get(0).getLatitude() * 1e6);
int lng = (int) (addressList.get(0).getLongitude() * 1e6);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// refresh your views here
super.onConfigurationChanged(newConfig);
}
class GetPlaces extends AsyncTask<String, Void, ArrayList<String>>
{
#Override
// three dots is java for an array of strings
protected ArrayList<String> doInBackground(String... args)
{
Log.d("gottaGo", "doInBackground");
ArrayList<String> predictionsArr = new ArrayList<String>();
try
{
URL googlePlaces = new URL(
// URLEncoder.encode(url,"UTF-8");
"https://maps.googleapis.com/maps/api/place/autocomplete/json?input="+ URLEncoder.encode(args[0].toString(), "UTF-8") +"&types=geocode&language=en&sensor=true&key=AIzaSyDYnuaL0x_7xGNqrEvYkgEB20_k-b4avOI");
URLConnection tc = googlePlaces.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
StringBuffer sb = new StringBuffer();
//take Google's legible JSON and turn it into one big string.
while ((line = in.readLine()) != null) {
sb.append(line);
System.out.println("Line: "+line);
}
//turn that string into a JSON object
JSONObject predictions = new JSONObject(sb.toString());
//now get the JSON array that's inside that object
JSONArray ja = new JSONArray(predictions.getString("predictions"));
System.out.println(ja.length());
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
//add each entry to our array
predictionsArr.add(jo.getString("description"));
}
} catch (IOException e){
Log.e("YourApp", "GetPlaces : doInBackground", e);
} catch (JSONException e){
Log.e("YourApp", "GetPlaces : doInBackground", e);
}
return predictionsArr;
}
//then our post
#Override
protected void onPostExecute(ArrayList<String> result)
{
Log.d("YourApp", "onPostExecute : " + result.size());
//update the adapter
adapter = new ArrayAdapter<String>(getBaseContext(), R.layout.item_list);
adapter.setNotifyOnChange(true);
//attach the adapter to textview
filltt.setAdapter(adapter);
for (String string : result)
{
Log.d("YourApp", "onPostExecute : result = " + string);
adapter.add(string);
adapter.notifyDataSetChanged();
}
Log.d("YourApp", "onPostExecute : autoCompleteAdapter" + adapter.getCount());
}
}
class LoadPlaces extends AsyncTask<String, String, PlacesList> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LocateActivity.this);
pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Places..."));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
* */
#SuppressLint("NewApi")
protected PlacesList doInBackground(String... args) {
// creating Places class object
googlePlaces = new GooglePlaces();
try {
if(gc.isPresent()){
List<Address> list = gc.getFromLocationName(locnm, 1);
Address address = list.get(0);
lat = address.getLatitude();
lng = address.getLongitude();
}
System.out.println("Lat Val: " + lat);
System.out.println("Long Val: " + lng);
String types = ""; // Listing places only cafes, restaurants
// Radius in meters - increase this value if you don't find any places
double radius = 1000; // 1000 meters
// get nearest places
nearPlaces = googlePlaces.search(lat,
lng, radius, types);
System.out.println("Places: "+nearPlaces);
// }
} catch (Exception e) {
e.printStackTrace();
}
return nearPlaces;
}
/**
* After completing background task Dismiss the progress dialog
* and show the data in UI
* Always use runOnUiThread(new Runnable()) to update UI from background
* thread, otherwise you will get error
* **/
protected void onPostExecute(PlacesList file_url) {
super.onPostExecute(file_url);
// dismiss the dialog after getting all products
pDialog.dismiss();
signal.countDown();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed Places into LISTVIEW
* */
// Get json response status
status = nearPlaces.status;
// Check for all possible status
if(status.equals("OK")){
// Successfully got places details
if (nearPlaces.results != null) {
// loop through each place
for (Place p : nearPlaces.results) {
HashMap<String, String> map = new HashMap<String, String>();
// Place reference won't display in listview - it will be hidden
// Place reference is used to get "place full details"
map.put(KEY_REFERENCE, p.reference);
// Place name
map.put(KEY_NAME, p.name);
System.out.println("Place Name: " +p.name);
// adding HashMap to ArrayList
placesListItems.add(map);
System.out.println("ITEM: " + placesListItems.get(0));
}
}
}
else if(status.equals("ZERO_RESULTS")){
}
else if(status.equals("UNKNOWN_ERROR"))
{
}
else if(status.equals("OVER_QUERY_LIMIT"))
{
}
else if(status.equals("REQUEST_DENIED"))
{
}
else if(status.equals("INVALID_REQUEST"))
{
}
else
{
}
}
});
try {
signal.await(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mapOverlays = mapView.getOverlays();
// Geopoint to place on map
geoPoint = new GeoPoint((int) (lat * 1E6),
(int) (lng * 1E6));
// Drawable marker icon
Drawable drawable_user = getResources()
.getDrawable(R.drawable.mark_red);
itemizedOverlay = new AddItemizedOverlay(drawable_user);
// Map overlay item
overlayitem = new OverlayItem(geoPoint, "Your Location",
"That is you!");
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
itemizedOverlay.populateNow();
// Drawable marker icon
Drawable drawable = getResources()
.getDrawable(R.drawable.mark_blue);
itemizedOverlay = new AddItemizedOverlay(drawable);
mc = mapView.getController();
// These values are used to get map boundary area
// The area where you can see all the markers on screen
int minLat = Integer.MAX_VALUE;
int minLong = Integer.MAX_VALUE;
int maxLat = Integer.MIN_VALUE;
int maxLong = Integer.MIN_VALUE;
// check for null in case it is null
if (nearPlaces.results != null) {
// loop through all the places
for (Place place : nearPlaces.results) {
latitude = place.geometry.location.lat; // latitude
longitude = place.geometry.location.lng; // longitude
// Geopoint to place on map
geoPoint = new GeoPoint((int) (latitude * 1E6),
(int) (longitude * 1E6));
// Map overlay item
overlayitem = new OverlayItem(geoPoint, place.name,
place.vicinity);
itemizedOverlay.addOverlay(overlayitem);
// calculating map boundary area
minLat = (int) Math.min( geoPoint.getLatitudeE6(), minLat );
minLong = (int) Math.min( geoPoint.getLongitudeE6(), minLong);
maxLat = (int) Math.max( geoPoint.getLatitudeE6(), maxLat );
maxLong = (int) Math.max( geoPoint.getLongitudeE6(), maxLong );
}
mapOverlays.add(itemizedOverlay);
// showing all overlay items
itemizedOverlay.populateNow();
}
// Adjusting the zoom level so that you can see all the markers on map
mapView.getController().zoomToSpan(Math.abs( minLat - maxLat ), Math.abs( minLong - maxLong ));
// Showing the center of the map
mc.animateTo(new GeoPoint((maxLat + minLat)/2, (maxLong + minLong)/2 ));
mapView.postInvalidate();
}
}
#Override
public boolean isLocationDisplayed() {
return false;
}
#Override
public boolean isRouteDisplayed() {
return false;
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
exitByBackKey();
//moveTaskToBack(false);
return true;
}
return super.onKeyDown(keyCode, event);
}
protected void exitByBackKey() {
AlertDialog alertbox = new AlertDialog.Builder(this)
.setMessage("Do you really want to Exit ?")
.setPositiveButton("YES", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
filltt.setText("");
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
//close();
}
})
.setNegativeButton("NO", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
}
})
.show();
}
}
Note: this code run perfectly in android 4.0 but when i test it in android 2.3, it gives me force close error. and throws me error like
Service not available.. and latitude and longtitude values are 0.
what is the solution for that? Please, help me to get out of this.
I got the solution.
package com.example.locatebased;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Hashtable;
import org.kxml.*;
import org.kxml.io.*;
import org.kxml.kdom.*;
import org.kxml.parser.*;
import android.util.Log;
public class Geocoding
{
Hashtable ht=null;
private boolean time=true;
private int count=0;
private String citystreetvalue=null;
public Geocoding()
{
System.out.println("Constructor call...");
ht=new Hashtable();
}
//***************************** Find Address of the latitude Longitude ***********
public String parseXml(String address)
{
try
{
System.out.println("Address is:" + address);
//URL mUrl = new URL("http://maps.google.com/maps/api/geocode/xml?address=tagore%20road%20rajkot&sensor=false");
URL mUrl = new URL("http://maps.google.com/maps/api/geocode/xml?address=" + address + "&sensor=false");
Log.e("Url",mUrl.toString());
HttpURLConnection mConn = (HttpURLConnection) mUrl.openConnection();
System.out.println("After address add...");
InputStream is = mConn.getInputStream();
Reader reader = new InputStreamReader(is);
XmlParser parser = new XmlParser(reader);
traverse(parser,"");
mConn.disconnect();
is.close();
System.out.println("Close all connection...");
if(ht.get("status").toString().equals("OK"))
{
System.out.println("result is Ok..." + ht.get("locality").toString() );
citystreetvalue=ht.get("latitude").toString() + ","+ ht.get("longitude").toString() +","+ht.get("locality").toString();
}
else
{
System.out.println("result is not Ok...");
citystreetvalue="InvalidLocation";
}
}
catch(Exception e)
{
System.out.println(e.toString());
}
System.out.println("before returen statement...");
return citystreetvalue;
}
public void traverse(XmlParser parser, String indent ) throws Exception
{
System.out.println("in Traverse method....");
boolean leave = false;
String title = new String();
String desc = new String();
do
{
ParseEvent event = parser.read ();
ParseEvent pe;
switch (event.getType())
{
// For example, <title>
case Xml.START_TAG:
// see API doc of StartTag for more access methods
// Pick up Title for display
if ("status".equals(event.getName()))
{
pe = parser.read();
title = pe.getText();
ht.put("status",title);
}
if(count<2)
{
if ("lat".equals(event.getName()))
{
pe = parser.read();
title = pe.getText();
ht.put("latitude",title);
count=count+1;
}
if ("lng".equals(event.getName()))
{
pe = parser.read();
desc = pe.getText();
ht.put("longitude",desc);
count=count+1;
}
}
if ("long_name".equals(event.getName()))
{
pe = parser.read();
title = pe.getText();
}
if ("type".equals(event.getName()))
{
pe = parser.read();
desc = pe.getText();
if(desc.equals("route"))
{
System.out.println("street is:" + title);
ht.put("street",title);
}
}
if("formatted_address".equals(event.getName()))
{
if(time)
{
pe = parser.read();
title = pe.getText();
ht.put("address",title);
time=false;
}
}
ht.put(desc,title);
traverse(parser,"") ; // recursion call for each <tag></tag>
break;
// For example </title?
case Xml.END_TAG:
leave = true;
break;
// For example </rss>
case Xml.END_DOCUMENT:
leave = true;
break;
// For example, the text between tags
case Xml.TEXT:
break;
case Xml.WHITESPACE:
break;
default:
}
} while( !leave );
}
}
now add below code in mainactivity class:
geocoding=new Geocoding();
locnm=locnm.replace(" ","%20");
String citystreetvalue=geocoding.parseXml(locnm);
System.out.println("string is:" + citystreetvalue);
if(citystreetvalue.equals("InvalidLocation"))
{
}else
{
String citystreetval[]=Split(citystreetvalue, ",");
String latstreet=citystreetval[2];
nlatitude=citystreetval[0];
nlongitude=citystreetval[1];
}

Categories

Resources