简体   繁体   中英

Unable to integrate g+ login in android

I have been trying to create a login page for my app and decided to use G+ as one of the means to login.

My code is as follows

public class LoginActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener {
String Name,Pass;
private static final int RC_SIGN_IN = 0;
private static final String TAG = "MainActivity";
private GoogleApiClient mGoogleApiClient;
private boolean mIntentInProgress;
private boolean mSignInClicked;
private ConnectionResult mConnectionResult;
SharedPreferences preferences;
SharedPreferences.Editor edit;
SignInButton b3;
final String App_id="WP74ib9AoAQtnKbJxgz5FkMSQLDq1raIIVyqIqup",C_key="FUXJl7JcyGP7cJuktrdoBr8WtnpzjpIQ9UK1UWc6";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    b3=(SignInButton)findViewById(R.id.button3);
    mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(Plus.API)
            .addConnectionCallbacks(this).addOnConnectionFailedListener(this)
            .addScope(Plus.SCOPE_PLUS_LOGIN).build();
    b3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            click();
        }
    });
}
public void click(){
    signInWithGplus();
    Toast.makeText(getApplicationContext(),"Inside click",Toast.LENGTH_SHORT).show();
}
protected void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
}

protected void onStop() {
    super.onStop();
    if (mGoogleApiClient.isConnected()) {
        mGoogleApiClient.disconnect();
    }
}
public void onConnectionFailed(ConnectionResult result) {
    if (!result.hasResolution()) {
        GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
                0).show();
        return;
    }
    if (!mIntentInProgress) {
        // Store the ConnectionResult for later usage
        mConnectionResult = result;
        if (mSignInClicked) {
            resolveSignInError();
        }
    }
}
@Override
protected void onActivityResult(int requestCode, int responseCode,
                                Intent intent) {
    if (requestCode == RC_SIGN_IN) {
        if (responseCode != RESULT_OK) {
            mSignInClicked = false;
        }

        mIntentInProgress = false;

        if (!mGoogleApiClient.isConnecting()) {
            mGoogleApiClient.connect();
        }
    }
}

@Override
public void onConnected(Bundle arg0) {
    mSignInClicked = false;
    getProfileInformation();
}

@Override
public void onConnectionSuspended(int arg0) {
    mGoogleApiClient.connect();

}
private void signInWithGplus() {
    if (!mGoogleApiClient.isConnecting()) {
        mSignInClicked = true;
        resolveSignInError();
    }
    else
        getProfileInformation();
}

/**
 * Method to resolve any signin errors
 * */
private void resolveSignInError() {
    if (mConnectionResult.hasResolution()) {
        try {
            mIntentInProgress = true;
            mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
        } catch (IntentSender.SendIntentException e) {
            Toast.makeText(getApplicationContext(),
                    "SignIn Error", Toast.LENGTH_LONG).show();
            mIntentInProgress = false;
            mGoogleApiClient.connect();
        }
    }
}

/**
 * Fetching user's information name, email, profile pic
 * */
private void getProfileInformation() {
    try {
        //Toast.makeText(getApplicationContext(), "Getting Profile",Toast.LENGTH_SHORT).show();
        if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
            Person currentPerson = Plus.PeopleApi
                    .getCurrentPerson(mGoogleApiClient);
            String personName = currentPerson.getDisplayName();
            String personPhotoUrl = currentPerson.getImage().getUrl();
            String personGooglePlusProfile = currentPerson.getUrl();
            String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
            Toast.makeText(getApplicationContext(),"Got Information",Toast.LENGTH_SHORT).show();
            Log.e(TAG, "Name: " + personName + ", plusProfile: "
                    + personGooglePlusProfile + ", email: " + email
                    + ", Image: " + personPhotoUrl);
        } else {
            //Toast.makeText(getApplicationContext(),
            //        "Person information is null", Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        // Toast.makeText(getApplicationContext(),
        //         "Person information is null", Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }
}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_login, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    //if (id == R.id.next) {
     //   return true;
    //}

    return super.onOptionsItemSelected(item);
}    }

I have implemented all the required functions needed to get the data.

When I launch the app and click the signin button I get a null pointer exception at

if (mConnectionResult.hasResolution())

The error log is as shown below

java.lang.NullPointerException
        at com.example.nirmal.playreskey.LoginActivity.resolveSignInError(LoginActivity.java:161)
        at com.example.nirmal.playreskey.LoginActivity.signInWithGplus(LoginActivity.java:151)
        at com.example.nirmal.playreskey.LoginActivity.click(LoginActivity.java:92)
        at com.example.nirmal.playreskey.LoginActivity$3.onClick(LoginActivity.java:87)
        at com.google.android.gms.common.SignInButton.onClick(Unknown Source)
        at android.view.View.performClick(View.java:4463)
        at android.view.View$PerformClick.run(View.java:18770)
        at android.os.Handler.handleCallback(Handler.java:808)
        at android.os.Handler.dispatchMessage(Handler.java:103)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:5292)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
        at dalvik.system.NativeStart.main(Native Method)

I have googled this type of error and found that this happens if we try to call the signin function before the onStart() is executed. So I created a toast to check if the onStart() is executed and then clicked the button then also I am getting the same error.

What is the cause of this error? and how to rectify it?

I followed tutorial from androidhive. It was almost same tutorial

private void resolveSignInError() {
        if (mConnectionResult != null) { //Added null check 
            if (mConnectionResult.hasResolution()) {
                try {
                    mIntentInProgress = true;
                    mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
                } catch (IntentSender.SendIntentException e) {
                    mIntentInProgress = false;
                    mGoogleApiClient.connect();
                }
            }
        }
    }

You can use this to handle your null exception in that method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM