Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caused by: java.lang.NullPointerException: Attempt to invoke interface method on a null object reference

I am having trouble submitting the highscores to android leaderboards. Right now the leaderboards are empty and nothing is being submitted. I have an int "oldScore" that needs to be submitted. Right now I am trying a piece of code to submit it but the activity crashes when called. My code:

public class GameOver extends BaseGameActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    private GoogleApiClient mGoogleApiClient;
    public static int score;

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

        mGoogleApiClient.connect();
        mGoogleApiClient = new GoogleApiClient.Builder(this)
        .addApi(Drive.API)
        .addScope(Drive.SCOPE_FILE)
        .addConnectionCallbacks(this)
        .addOnConnectionFailedListener(this)
        .build();

        int newScore = GameOver.score;

        SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);

        int oldScore = prefs.getInt("key", 0);
        if (newScore > oldScore) {
            SharedPreferences.Editor edit = prefs.edit();
            edit.putInt("key", newScore);
            edit.commit();

            EditText HighScore = (EditText) findViewById(R.id.HighScoreT);
            HighScore.setText("" + newScore);
        } else {
            EditText HighScore = (EditText) findViewById(R.id.HighScoreT);
            HighScore.setText("" + oldScore);
            Games.Leaderboards.submitScoreImmediate(getApiClient(),String.valueOf(R.string.number_guesses_leaderboard), oldScore);
        }
    }

Logcat:

Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'void com.google.android.gms.common.api.GoogleApiClient.connect()' on a null object reference

like image 362
l7ivine Avatar asked Nov 28 '22 14:11

l7ivine


1 Answers

The statement

mGoogleApiClient.connect();

should appear after mGoogleApiClient has been instantiated

like image 136
Reimeus Avatar answered Dec 04 '22 14:12

Reimeus