Search code examples
androidgoogle-api-client

Issue connecting GoogleApiClient in multiple activities


I was, for the first time, trying to implement a google play services leader board but have some issue.

I have the show leaderboard button in the main activity, so I initialize an GoogleApiClient in MainActivity, all good so far - google connects, and a blank leaderboard.

The score that actually fills the leaderboard is obtained from second activity, the GameActivity. I create yet another instance of GoogleApiClient and try connecting it. But.. it always fails, even after calling apiClient.connect()

Am I doing something wrong? Is only 1 client allowed throughout the program?

I use this code in both of the activities to initialize:

apiClient = new GoogleApiClient.Builder(this)
            .addApi(Games.API)
            .addScope(Games.SCOPE_GAMES)
            .enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
                @Override
                public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
                    Toast.makeText(LevelSelector.this, "Failed to connect to google play", Toast.LENGTH_LONG).show();
                }
            })
            .build();

I call leaderboard from the main activity

    leaderboardTextView = (TextView) findViewById(R.id.leaderboard_button);
    leaderboardTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivityForResult(
                    Games.Leaderboards.getLeaderboardIntent(apiClient,
                            getString(R.string.leaderboard_most_stars)), 0);
        }
    });

And the score is submitted to leaderboard from a different activity

private void updateScore(){
    if(!apiClient.isConnected()){
        apiClient.connect();
    }
    //Always returns false.
    if(apiClient.isConnected()) {
        Games.Leaderboards.submitScore(apiClient,
                getString(R.string.leaderboard_most_stars),
                totalStars);
    }
}

Solution

  • Only one API client is allowed in an app. Make your apiClient public static and access it from any class using MainActivity.apiClient