Android GPS - 向排行榜提交高分

时间:2016-11-25 16:06:09

标签: android google-play-services google-play-games

我正在尝试向我的排行榜提交高分,但由于某种原因它无效。该应用程序不会崩溃,并且logcat中没有错误。

当用户未登录时,会弹出Google Play游戏。目前,当用户获得新的高分时,该应用程序会自动显示吐司。所以看来我的Asynctask没有正确编码?

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);
        }
    }
}
}

1 个答案:

答案 0 :(得分:1)

您似乎在声明mGoogleAPIClient但实际上没有创建它的实例,因此您的&#39; NullPointerException&#39;

在您尝试使用mGoogleAPIClient之前,请添加以下内容以创建它.......

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();

有关详细信息,请参阅Here

希望这有帮助