Issue
I am trying to display address of the location by providing its coordinates using object of Geocoder class but every time i receive 0 number of addresses.
Here is my activity code:
package com.packr.activities;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.packr.R;
import com.packr.classes.LocationProvider;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class PickupActivity extends FragmentActivity implements LocationProvider.LocationCallback {
public static final String TAG = PickupActivity.class.getSimpleName();
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private LocationProvider mLocationProvider;
private LatLng center;
private TextView pickupMarker;
private LinearLayout markerLayout;
private List<Address> addresses;
private TextView address;
private Geocoder geocoder;
private Marker m;
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pickup);
initialize();
onClick();
setUpMapIfNeeded();
mLocationProvider = new LocationProvider(this, this);
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
mLocationProvider.connect();
}
@Override
protected void onPause() {
super.onPause();
mLocationProvider.disconnect();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
//mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.setMyLocationEnabled(true);
}
public void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
mMap.setMyLocationEnabled(true);
//mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng).zoom(19f).tilt(0).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
mMap.clear();
mMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition arg0) {
// TODO Auto-generated method stub
center = mMap.getCameraPosition().target;
pickupMarker.setText(" Set your Location ");
mMap.clear();
try {
new GetLocationAsync(center.latitude, center.longitude)
.execute();
Log.e("Coordinates",(center.longitude + "" + center.latitude));
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void initialize(){
pickupMarker = (TextView)findViewById(R.id.locationMarkertext);
markerLayout = (LinearLayout)findViewById(R.id.locationMarker);
address = (TextView)findViewById(R.id.addressText);
}
public void onClick() {
markerLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
LatLng latLng1 = new LatLng(center.latitude,
center.longitude);
m = mMap.addMarker(new MarkerOptions()
.position(latLng1)
.title(" Set your Location ")
.snippet("Arindam")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_cast_light)));
m.setDraggable(true);
address.setText((center.latitude+","+center.longitude));
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private class GetLocationAsync extends AsyncTask<String, Void, String> {
// boolean duplicateResponse;
double x, y;
StringBuffer str;
public GetLocationAsync(double latitude, double longitude) {
// TODO Auto-generated constructor stub
x = latitude;
y = longitude;
}
@Override
protected void onPreExecute() {
address.setText(" Getting your location ");
}
@Override
protected String doInBackground(String... params) {
try {
geocoder = new Geocoder(getApplicationContext());
addresses = geocoder.getFromLocation(x,y,1);
str = new StringBuffer();
if (Geocoder.isPresent()) {
if( null!=addresses&&addresses.size()>0){
Address returnAddress = addresses.get(0);
String localityString = returnAddress.getLocality();
String city = returnAddress.getCountryName();
String region_code = returnAddress.getCountryCode();
String zipcode = returnAddress.getPostalCode();
str.append(localityString).append("");
str.append(city).append("").append(region_code).append("");
str.append(zipcode).append("");}
} else {
}
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
return null;
}
@Override
protected void onPostExecute(String result) {
try {
if (!addresses.isEmpty())
address.setText(addresses.get(0).getAddressLine(0)
+ addresses.get(0).getAddressLine(1) + " ");
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onProgressUpdate(Void... values) {
}
}
}
I have created a separate abstract interface class for location provider which is as follows:
package com.packr.classes;
/**
* Created by addy on 27/06/15.
*/
import android.app.Activity;
import android.content.Context;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
/**
* Created by arindam on 27/06/15
*/
public class LocationProvider implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
public abstract interface LocationCallback {
public void handleNewLocation(Location location);
}
public static final String TAG = LocationProvider.class.getSimpleName();
/*
* Define a request code to send to Google Play services
* This code is returned in Activity.onActivityResult
*/
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private LocationCallback mLocationCallback;
private Context mContext;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
public LocationProvider(Context context, LocationCallback callback) {
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationCallback = callback;
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
mContext = context;
}
public void connect() {
mGoogleApiClient.connect();
}
public void disconnect() {
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
@Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Location services connected.");
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
else {
mLocationCallback.handleNewLocation(location);
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution() && mContext instanceof Activity) {
try {
Activity activity = (Activity)mContext;
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(activity, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
@Override
public void onLocationChanged(Location location) {
mLocationCallback.handleNewLocation(location);
}
}
Underneath is my manifest file :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.packr" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but are recommended.
-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="@string/google_maps_key" />
<activity
android:name=".activities.PickupActivity"
android:label="@string/title_activity_pickup" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Can anyone explain me why am I getting 0 number of results every time. I have found similar questions but it didn't help.
Solution
Your issue is here:
public GetLocationAsync(double latitude, double longitude) {
// TODO Auto-generated constructor stub
x = latitude;
y = longitude;
}
x is longitude and y is latitude!
Answered By - N Dorigatti
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.