Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to find current location inside Fragment

I am trying to get current location using Places API. Please find the code below

 public class PlaceFragment extends Fragment implements View.OnClickListener {

private Button currentLocation;

private View myFragmentView;

private GoogleApiClient mGoogleApiClient;

private static final int MY_PERMISSIONS_REQUEST_LOCATION = 101;


public PlaceFragment() {
    // Required empty public constructor
}


@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    mGoogleApiClient = new GoogleApiClient
            .Builder(getActivity())
            .addApi(Places.GEO_DATA_API)
            .addApi(Places.PLACE_DETECTION_API)
            .build();

}

@Override
public void onStart() {

    super.onStart();
    if (mGoogleApiClient != null)
        mGoogleApiClient.connect();

}

@Override
public void onStop() {

    if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
        mGoogleApiClient.disconnect();
    }
    super.onStop();

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    myFragmentView = inflater.inflate(R.layout.fragment_place, container, false);

    currentLocation = (Button) myFragmentView.findViewById(R.id.currentLocation);
    currentLocation.setOnClickListener(this);

    return myFragmentView;
}

@Override
public void onClick(View v) {

    if (v.getId() == R.id.currentLocation) {

        int permissionCheck = ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.ACCESS_FINE_LOCATION);

        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION);
        } else {
            getCurrentLocation();
        }
    }
}


@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_LOCATION: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.
                getCurrentLocation();

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}


private void getCurrentLocation() {

    PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi.getCurrentPlace(mGoogleApiClient, null);
    result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
        @Override
        public void onResult(PlaceLikelihoodBuffer likelyPlaces) {

            PlaceLikelihood placeLikelihood = likelyPlaces.get(0);
            String content = "";
            if (placeLikelihood != null && placeLikelihood.getPlace() != null && !TextUtils.isEmpty(placeLikelihood.getPlace().getName()))
                content = "Most likely place: " + placeLikelihood.getPlace().getName() + "\n";
            if (placeLikelihood != null)
                content += "Percent change of being there: " + (int) (placeLikelihood.getLikelihood() * 100) + "%";
            System.out.println(content);

            likelyPlaces.release();
        }
    });
}
}

But neither I am getting permission dialog nor any valid current location, I have tried by giving access as well by removing access. This is the error I am getting in monitor

 E/Places: Timed out waiting for a location for getCurrentPlace
 11-11 10:41:46.417 2591-2591/com.kumarpratik.WhatsAround E/UncaughtException: java.lang.IllegalStateException
                                                                              at com.google.android.gms.common.internal.zzac.zzbr(Unknown Source)
                                                                              at com.google.android.gms.common.data.zzc.zzfz(Unknown Source)
                                                                              at com.google.android.gms.common.data.zzc.<init>(Unknown Source)
                                                                              at com.google.android.gms.location.places.internal.zzt.<init>(Unknown Source)
                                                                              at com.google.android.gms.location.places.internal.zzn.<init>(Unknown Source)
                                                                              at com.google.android.gms.location.places.PlaceLikelihoodBuffer.get(Unknown Source)
                                                                              at com.kumarpratik.WhatsAround.fragment.PlaceFragment$1.onResult(PlaceFragment.java:147)
                                                                              at com.kumarpratik.WhatsAround.fragment.PlaceFragment$1.onResult(PlaceFragment.java:143)
                                                                              at com.google.android.gms.internal.zzqe$zza.zzb(Unknown Source)
                                                                              at com.google.android.gms.internal.zzqe$zza.handleMessage(Unknown Source)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                              at android.os.Looper.loop(Looper.java:135)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5292)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at java.lang.reflect.Method.invoke(Method.java:372)
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
11-11 10:41:46.664 2591-2591/com.kumarpratik.WhatsAround E/AndroidRuntime: FATAL EXCEPTION: main
                                                                       Process: com.kumarpratik.WhatsAround, PID: 2591
                                                                       java.lang.IllegalStateException
                                                                           at com.google.android.gms.common.internal.zzac.zzbr(Unknown Source)
                                                                           at com.google.android.gms.common.data.zzc.zzfz(Unknown Source)
                                                                           at com.google.android.gms.common.data.zzc.<init>(Unknown Source)
                                                                           at com.google.android.gms.location.places.internal.zzt.<init>(Unknown Source)
                                                                           at com.google.android.gms.location.places.internal.zzn.<init>(Unknown Source)
                                                                           at com.google.android.gms.location.places.PlaceLikelihoodBuffer.get(Unknown Source)
                                                                           at com.kumarpratik.WhatsAround.fragment.PlaceFragment$1.onResult(PlaceFragment.java:147)
                                                                           at com.kumarpratik.WhatsAround.fragment.PlaceFragment$1.onResult(PlaceFragment.java:143)
                                                                           at com.google.android.gms.internal.zzqe$zza.zzb(Unknown Source)
                                                                           at com.google.android.gms.internal.zzqe$zza.handleMessage(Unknown Source)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                           at android.os.Looper.loop(Looper.java:135)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:5292)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at java.lang.reflect.Method.invoke(Method.java:372)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
11-11 10:42:33.120 18739-3697/? E/GeofenceHelper: Failed: remove geofences by PendingIntent

This is my manifest file

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.INTERNET" />

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true"/>

<application android:name=".common.AppController" android:allowBackup="true" android:debuggable="true"
android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true"
android:theme="@style/MyMaterialTheme">
<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
<meta-data android:name="com.google.android.geo.API_KEY" android:value="@string/googlekey" />

<activity android:name=".activity.MainActivity" android:label="@string/title_activity_welcome"
    android:launchMode="standard" android:theme="@style/MyMaterialTheme" />
<activity android:name=".activity.IntroActivity" android:theme="@style/MyMaterialTheme">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
<activity android:name=".activity.SetLocationActivity" android:parentActivityName=".activity.MainActivity">

    <!-- Parent activity meta-data to support 4.0 and lower -->
    <meta-data android:name="android.support.PARENT_ACTIVITY" android:value="com.kumarpratik.WhatsAround.activity.MainActivity" />
</activity>

EDIT

I am getting

PlaceLikelihoodBuffer{status=Status{statusCode=ERROR, resolution=null}, attributions=null} in onResult()

like image 272
Pratik Avatar asked Nov 11 '16 05:11

Pratik


4 Answers

Ok, I finally got it working, posting it if someone finds it useful

 locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);

        // getting GPS status
        checkGPS = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        checkNetwork = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!checkGPS && !checkNetwork) {
            Toast.makeText(mContext, "No Service Provider Available", Toast.LENGTH_SHORT).show();
        } else {
            this.canGetLocation = true;
            // First get location from Network Provider
            if (checkNetwork) {
                Toast.makeText(mContext, "Network", Toast.LENGTH_SHORT).show();

                try {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        loc = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                    }

                    if (loc != null) {
                        latitude = loc.getLatitude();
                        longitude = loc.getLongitude();
                    }
                } catch (SecurityException e) {

                }
            }
        }
        // if GPS Enabled get lat/long using GPS Services
        if (checkGPS) {
            Toast.makeText(mContext, "GPS", Toast.LENGTH_SHORT).show();
            if (loc == null) {
                try {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        loc = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (loc != null) {
                            latitude = loc.getLatitude();
                            longitude = loc.getLongitude();
                        }
                    }
                } catch (SecurityException e) {

                }
            }
        }
like image 59
Pratik Avatar answered Oct 19 '22 04:10

Pratik


It happens when you and your dependencies using different version of Google Play Services - GPS. So you need to updated them into same version, or just update in project to the latest one. So first of all, check you Build Gradle file to contains error warnings, related to Google Play Dependencies. And try to update it!

One of the Error:

Execution failed for task ':app:processDebugGoogleServices'. Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available here) or updating the version of com.google.android.gms to 8.3.0.

    /*
     * Update GPA regarding to issue with
     * conflict google services dependencies!
     */
    compile 'com.google.android.gms:play-services-base:9.6.1'
    // Google Play Services Maps
    compile 'com.google.android.gms:play-services-maps:9.6.1'
like image 42
GensaGames Avatar answered Nov 19 '22 18:11

GensaGames


Implement & register for googleapi connection listeners and override onLocationChange callback to get location updates

like image 1
NIPHIN Avatar answered Nov 19 '22 17:11

NIPHIN


you can not give same permission in manifest file.and also check GCM project in Enable/Disable option. check following link to give info about map.

http://wptrafficanalyzer.in/blog/showing-current-location-in-google-maps-using-api-v2-with-supportmapfragment/

like image 1
Idrish Multani Avatar answered Nov 19 '22 17:11

Idrish Multani