2

I'm trying to submit a highscore to my leaderboards, but for some reason it doesn't work. The app doesn't crash and there is no error in the logcat.

When the user isn't logged in there will be a pop-up of Google Play Games. Currently when a user gets a new highscore the app automatically shows the toast. So it seems my Asynctask is not correctly coded?

public class result extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks{

public GoogleApiClient mGoogleApiClient;
private static int RC_SIGN_IN = 9001;
private boolean mResolvingConnectionFailure = false;
private boolean mAutoStartSignInFlow = true;
private boolean mSignInClicked = false;

public int HighScore;

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

    // Create the Google Api Client with access to the Play Games services
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(Games.API).addScope(Games.SCOPE_GAMES)
            // add other APIs and scopes here as needed
            .build();

    TextView scoreLabel = (TextView) findViewById(R.id.scoreLabel);
    TextView highScoreLabel = (TextView) findViewById(R.id.highScoreLabel);

    int score = getIntent().getIntExtra("SCORE", 0);
    scoreLabel.setText(score + "");

    SharedPreferences settings = getSharedPreferences("HIGH_SCORE", Context.MODE_PRIVATE);
    HighScore = settings.getInt("HIGH_SCORE", 0);

    if (score > HighScore) {
        highScoreLabel.setText("High Score : " + score);
        submitScore(score);
        // Update High Score
        SharedPreferences.Editor editor = settings.edit();
        editor.putInt("HIGH_SCORE", score);
        editor.commit();

    } else {
        highScoreLabel.setText("High Score : " + HighScore);
    }

}

public void tryAgain(View view) {
    startActivity(new Intent(getApplicationContext(), start.class));
}


// Disable Return Button
@Override
public boolean dispatchKeyEvent(KeyEvent event) {

    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (event.getKeyCode()) {
            case KeyEvent.KEYCODE_BACK:
                return true;
        }
    }

    return super.dispatchKeyEvent(event);
}

public class LoadData extends AsyncTask<Void, Void, Void> {

    ProgressDialog pdLoading = new ProgressDialog(result.this);
    //declare other objects as per your need

    @Override
    protected void onPreExecute()
    {
        pdLoading.setMessage("\tSending highscore to leaderboard...");
        pdLoading.show();

        //do initialization of required objects objects here
    };
    @Override
    protected Void doInBackground(Void... params)
    {
        Games.Leaderboards.submitScoreImmediate(mGoogleApiClient, getString(R.string.leaderboard_top_players), HighScore);
        //do loading operation here
        return null;
    }
    @Override
    protected void onPostExecute(Void result)
    {
        super.onPostExecute(result);
        pdLoading.dismiss();
    };
}

//Start GPS
@Override
public void onConnected(@Nullable Bundle bundle) {

}

@Override
public void onConnectionSuspended(int i) {
    // Attempt to reconnect
    mGoogleApiClient.connect();
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    if (mResolvingConnectionFailure) {
        // Already resolving
        return;
    }

    // If the sign in button was clicked or if auto sign-in is enabled,
    // launch the sign-in flow
    if (mSignInClicked || mAutoStartSignInFlow) {
        mAutoStartSignInFlow = false;
        mSignInClicked = false;
        mResolvingConnectionFailure = true;

        // Attempt to resolve the connection failure using BaseGameUtils.
        // The R.string.signin_other_error value should reference a generic
        // error string in your strings.xml file, such as "There was
        // an issue with sign in, please try again later."
        if (!BaseGameUtils.resolveConnectionFailure(this,
                mGoogleApiClient, connectionResult,
                RC_SIGN_IN, getString(R.string.signin_other_error))) {
            mResolvingConnectionFailure = false;
        }
    }

    // Put code here to display the sign-in button
}

public void submitScore(long highscore){
    if (mGoogleApiClient.isConnected()){
        LoadData task = new LoadData();
        task.execute();
        //Games.Leaderboards.submitScoreImmediate(mGoogleApiClient, getString(R.string.leaderboard_top_players), highscore);
    }else{
        Toast.makeText(this, "Unable to submit highscore", Toast.LENGTH_SHORT).show();
    }
}

@Override
protected void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
}

@Override
protected void onStop() {
    super.onStop();
    mGoogleApiClient.disconnect();
}

protected void onActivityResult(int requestCode, int resultCode,
                                Intent intent) {
    if (requestCode == RC_SIGN_IN) {
        mSignInClicked = false;
        mResolvingConnectionFailure = false;
        if (resultCode == RESULT_OK) {
            mGoogleApiClient.connect();
        } else {
            // Bring up an error dialog to alert the user that sign-in
            // failed. The R.string.signin_failure should reference an error
            // string in your strings.xml file that tells the user they
            // could not be signed in, such as "Unable to sign in."
            BaseGameUtils.showActivityResultError(this,
                    requestCode, resultCode, R.string.signin_failure);
        }
    }
}
}
Enzokie
  • 7,365
  • 6
  • 33
  • 39
MrN2017
  • 39
  • 3
  • 13

1 Answers1

1

You seem to be declaring mGoogleAPIClient but not actually creating an instance of it, hence your 'NullPointerException'

Before you try to use mGoogleAPIClient, add the following to create it.....

mGoogleApiClient = new GoogleApiClient.Builder(this)
    .addConnectionCallbacks(this)
    .addOnConnectionFailedListener(this)
    .addApi(Games.API).addScope(Games.SCOPE_GAMES)
    // add other APIs and scopes here as needed
    .build();

See Here for more details

Hope this helps

Zippy
  • 3,826
  • 5
  • 43
  • 96
  • I thought if I created that in my start.class it will stay connected through all classes. I will try this out. – MrN2017 Dec 20 '16 at 10:51
  • Hi @MisterN, where do you create your actual mGoogleAPIClient object? (I didn't realise you had already created one elsewhere) If you've declared and create one somewhere else, then you're declaring another here in Result - which isn't being created. When you call submitScore, it's trying to use this one, hence the nullPointer. – Zippy Dec 20 '16 at 12:58
  • I did what you said. But I still can't figure out what is wrong with my code. If you can take a look at it I really appreciate that. – MrN2017 Dec 24 '16 at 22:16
  • 1
    Hi, you seem to be calling submitScore in onCreate but not calling mGoogleAPIClient.connect() until onStart(), so when submitScore checks the connection it will return false, hence the toast. But I'm unsure how you've structured this, are you starting this 'result' activity every time a user gets a high score? Why not create the (mGoogleAPIClient) object once (in your launcher activity for example), attempt to connect it and then just query it whenever you need to. Of course as I said before, if you create it in another Activity, you'd need to find a way to work with the same instance of it. – Zippy Dec 26 '16 at 01:48