2

I am testing with the location services in Android and I was following strictly the developer instructions (here :Google dev. link) on how to do this, but no luck what so ever. In my layout fine I have just two TextViews to display the latitude and longitude of the Location object. I should mention that I am using Genymotion VM with GPS enabled.

This is my code in MainActivity:

package criminalintent.android.bignerdranch.com.testgetlocation;

import android.app.Activity;
import android.location.Location;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.location.LocationServices;

public class MainActivity extends Activity implements
    GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
GoogleApiClient mGoogleApiClient;
private TextView mLatitudeText;
private TextView mLongitudeText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mLatitudeText=  (TextView) findViewById(R.id.latitudeTextView);
    mLongitudeText = (TextView) findViewById(R.id.longitudeTextView);

    buildGoogleApiClient();


}

protected synchronized void buildGoogleApiClient() {
    Toast.makeText(this,"buildGoogleApiClient",Toast.LENGTH_SHORT).show();
     mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}

@Override
public void onConnected(Bundle bundle) {
    Toast.makeText(this,"onConnected",Toast.LENGTH_SHORT).show();
   Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient);
    if (mLastLocation != null) {
        mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
        mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
    }
}

@Override
public void onConnectionSuspended(int i) {
    Toast.makeText(this,"onConnectionSuspended",Toast.LENGTH_SHORT).show();
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    Toast.makeText(this,"onConnectionFailed",Toast.LENGTH_SHORT).show();
}
}

I have added the permission of getting the location services in the Manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="criminalintent.android.bignerdranch.com.testgetlocation" >

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

This is my module build.gradle file code:

apply plugin: 'com.android.application'

android {
compileSdkVersion 22
buildToolsVersion "21.1.2"

defaultConfig {
    applicationId "criminalintent.android.bignerdranch.com.testgetlocation"
    minSdkVersion 14
    targetSdkVersion 22
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),   'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.1.1'
compile 'com.google.android.gms:play-services:7.3.0'
}
Georgi Koemdzhiev
  • 11,421
  • 18
  • 62
  • 126

1 Answers1

2

You were missing the call to connect.

Add the call to connect() in onCreate() after you call buildGoogleApiClient():

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mLatitudeText=  (TextView) findViewById(R.id.latitudeTextView);
    mLongitudeText = (TextView) findViewById(R.id.longitudeTextView);

    buildGoogleApiClient();

    mGoogleApiClient.connect(); //add this here

}

Note that even with this fix, the call to getLastLocation() will have a high tendency to give you a null location.

I would suggest registering a listener if you get a null location, take a look at this answer for info on how to do that.

Edit: Since I already had your code running, I went ahead and added a location listener. Note that in this code I added a call to removeLocationUpdates() as soon as the first onLocationChanged() callback occurs, just as an example:

import android.os.Bundle;
import android.app.Activity;
import android.location.Location;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationListener;

public class MainActivity extends Activity implements
        GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    private TextView mLatitudeText;
    private TextView mLongitudeText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mLatitudeText=  (TextView) findViewById(R.id.latitudeTextView);
        mLongitudeText = (TextView) findViewById(R.id.longitudeTextView);

        buildGoogleApiClient();

        mGoogleApiClient.connect(); //add this here

    }

    protected synchronized void buildGoogleApiClient() {
        Toast.makeText(this,"buildGoogleApiClient",Toast.LENGTH_SHORT).show();
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

    @Override
    public void onConnected(Bundle bundle) {
        Toast.makeText(this,"onConnected",Toast.LENGTH_SHORT).show();
        Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);
        if (mLastLocation != null) {
            mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
            mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
        }

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(10000); //10 seconds
        mLocationRequest.setFastestInterval(5000); //5 seconds
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        mLocationRequest.setSmallestDisplacement(1); //1 meter

        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);



    }

    @Override
    public void onConnectionSuspended(int i) {
        Toast.makeText(this,"onConnectionSuspended",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Toast.makeText(this,"onConnectionFailed",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onLocationChanged(Location location) {

        Toast.makeText(this,"Location Changed",Toast.LENGTH_SHORT).show();

        mLatitudeText.setText(String.valueOf(location.getLatitude()));
        mLongitudeText.setText(String.valueOf(location.getLongitude()));

        //If you only need one location, unregister the listener
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);

    }

}

Also note that you should add this to your AndroidManifest.xml inside the application tag:

    <meta-data
    android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />
Community
  • 1
  • 1
Daniel Nugent
  • 43,104
  • 15
  • 109
  • 137