Android Login Using Google+

google+

In this tutorial we will learn how to login using Google+ and retrieve list of friends with their profile pictures.

First of all we will make an application at google developer console. You can follow https://developers.google.com/+/mobile/android/getting-started for help.

If using android studio you can set dependency in build.grade in app folder like this:

Screen Shot 2015-08-22 at 2.53.56 am

After that we will make two activities, one for signing in and another one for showing profile and friend list.

In MainActivity.java we will initialize the GoogleApiClient object, request the PLUS_LOGIN and PLUS_PROFILE scopes.

  mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(Plus.API)
                .addScope(Plus.SCOPE_PLUS_LOGIN)
                .addScope(Plus.SCOPE_PLUS_PROFILE)
                .build();

The GoogleApiClient object wraps a ServiceConnection to Google Play services; this GoogleApiClient object is used to communicate with the Google+ API and becomes functional after the asynchronous connection has been established with the service.

We will use the connect method of GoogleApiClient on loginButton click:

loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mGoogleApiClient.connect();
            }
        });

In onConnected() we will get the profile details of the account with which we have logged in.

@Override
    public void onConnected(Bundle bundle) {
       // loginButton.setText("Signout");
//        Set<String> sets=
        pdialog=new ProgressDialog(MainActivity.this);
        pdialog.setMessage("Loading..");
        pdialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pdialog.setCancelable(false);
        pdialog.show();
        Plus.PeopleApi.loadVisible(mGoogleApiClient, null)
                .setResultCallback(this);
        if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
            Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);

            String personName = currentPerson.getDisplayName();
            String personPhoto = currentPerson.getImage().getUrl();
            System.out.println(personPhoto);
            //We can adjust size of image according to our requirements: here 200 is the size of image
            String personImage=personPhoto.substring(0,personPhoto.lastIndexOf("=")+1)+"200";
            System.out.println(personImage);
            String personGooglePlusProfile = currentPerson.getUrl();
            SharedPreferences.Editor edit=shared.edit();
            edit.putString("userName",personName);
            edit.putString("userImageUrl",personImage);
            edit.putString("userProfile",personGooglePlusProfile);
            edit.commit();


        }
    }

We will implement another interface ResultCallback for getting visible friend list:

public class MainActivity extends AppCompatActivity implements
        GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, ResultCallback<People.LoadPeopleResult> {

After that we will get the list of friends names and profile pictures using:

@Override
    public void onResult(People.LoadPeopleResult peopleData) {
        if (peopleData.getStatus().getStatusCode() == CommonStatusCodes.SUCCESS) {
            PersonBuffer personBuffer = peopleData.getPersonBuffer();
            try {
                int count = personBuffer.getCount();
                for (int i = 0; i < count; i++) {
                    Log.d("MAINACTIVITY", "Display name: " + personBuffer.get(i).getImage().getUrl());
                    friendNames.add(personBuffer.get(i).getDisplayName());
                    String usrImage=personBuffer.get(i).getImage().getUrl().substring(0, personBuffer.get(i).getImage().getUrl().lastIndexOf("=") + 1)+"60";
                    friendImages.add(usrImage);
                }
                personBuffer.close();
                if(pdialog!=null){
                    pdialog.dismiss();
                }
                startActivity(new Intent(MainActivity.this,ProfileActivity.class).putStringArrayListExtra("friendsNamesList",friendNames).putStringArrayListExtra("friendsImagesList",friendImages));
            } finally {
                personBuffer.release();
            }
        } else {
            Log.e("MAINACTIVITY", "Error requesting visible circles: " + peopleData.getStatus());
        }
    }

I have used picasso library which we have already added to this project via build.grade. For eclipse users, they can download library from http://square.github.io/picasso/ and add to their project.

Finally in ProfileActivity we will show profile details of the account with which we have logged in and the list of visible friends with their profile pictures.

public class ProfileActivity extends AppCompatActivity{
    SharedPreferences shared;
    ImageView userImage;
    TextView userName;
    ArrayList<String> userNames,userImages;
    CustomAdapter usersAdapter;
    ListView usersList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);
        shared=getSharedPreferences("demoGoogleLogin", Context.MODE_PRIVATE);
        userImage=(ImageView) findViewById(R.id.imageView);
        userName=(TextView) findViewById(R.id.textView);
        usersList=(ListView) findViewById(R.id.userslist);
        userNames=new ArrayList<>();
        userImages=new ArrayList<>();
        Picasso.with(ProfileActivity.this).load(shared.getString("userImageUrl","")).transform(new CircleTransform()).placeholder(R.drawable.icon_profile).error(R.drawable.icon_profile).resize(200,200).into(userImage);
        userName.setText("You are logged in as: "+shared.getString("userName",""));
        userNames=getIntent().getStringArrayListExtra("friendsNamesList");
        userImages=getIntent().getStringArrayListExtra("friendsImagesList");
        usersAdapter=new CustomAdapter(ProfileActivity.this,userNames,userImages);
        usersList.setAdapter(usersAdapter);

    }

}

imagecollage

DOWNLOAD FULL CODE

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s