Login with FaceBook example

In this example we learn how to login using facebook with a simple example along with getting User's name, Profile picture, Email Id, Birthday along with Gender.

  • Things we need to do:

  1. Login to facebook for developers and create an App in it.
  2. Integrate facebook SDK in to your App in android studio.
  3. Code for your App.
Login in to facebook for developers with this link Facebook For Developers
  • You can login with your facebook credentials itself.


  • Create an App in facebook developers console. Give your own app name I have given my own app name as LoginAndroidStudio.

  • Create your app and you will get APP ID from facebook copy and paste it in your strings.xml file.
     

 <string name="fb_id">paste your add id here</string>










  • Now scroll down and click on add platform in your facebook developers page.



  • After clicking on the button you will get scrolled down. Fill the fields like your app's package and activity in which you are going to place fb login button and keyhash of your IDE.



  • Add this method in your activity and run the app to get your key hash.

package infinite.hss.com.loginandroidstudio;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class MainActivity extends AppCompatActivity {

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

        PrintHashKey();

    }

    public void PrintHashKey() {
        // Add this to print the key hash in log cat
        try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    "infinite.hss.com.loginandroidstudio",
                    PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.e("KEYHASH:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
        } catch (PackageManager.NameNotFoundException e) {

        } catch (NoSuchAlgorithmException e) {

        }
    }
}





  • Add this permissions and your app id in Manifest.xml


    
<uses-permission android:name="android.permission.INTERNET"/>   





  • Add this meta data parameter in your Manifest.xml before activity parameter. 


   
 <meta-data android:name="com.facebook.sdk.ApplicationId"    
      android:value="@string/fb_id"/>




  • Now add this dependency in your build.gradle file.

compile 'com.facebook.android:facebook-android-sdk:4.0.0' 



  • After adding all these details now run your app you will get keyhash in your log cat copy and paste it in your facebook developers page and click save.
  • After clicking save button one pop up will be shown to your click "Use this package name".




  
  • Now setup for your app in facebook is done, all you need to do now is code in Android Studio.
  • Before coding the project copy and paste this dependency into build.gradle.

     

compile 'com.squareup.picasso:picasso:2.5.2'


  • Picasso library is used to show image's and image url's into imageView.
  • Now copy and paste the following xml code into your activity_main.xml file.

File: activity_main.xml:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="infinite.hss.com.loginandroidstudio.MainActivity">


    <ImageView
        android:id="@+id/img_profile"
        android:layout_width="120dp"
        android:layout_height="120dp"
        android:layout_margin="20dp"
        android:src="@drawable/user_pic" />

    <TextView
        android:id="@+id/txt_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="Name"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/txt_email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="Email Id"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/txt_gender"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="Gender"
        android:textStyle="bold" />


    <TextView
        android:id="@+id/txt_bDay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="Birthday"
        android:textStyle="bold" />


    <com.facebook.login.widget.LoginButton
        android:id="@+id/login_buttonFB"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_margin="30dp" />

    <Button
        android:id="@+id/btn_logOut"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:background="@color/colorPrimary"
        android:text="Logout"
        android:textColor="#ffffff"
        android:visibility="gone" />


</LinearLayout>



  • Now copy and paste the following java code into your MainActivity.java file.

File: MainActivity.java:


package infinite.hss.com.loginandroidstudio;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

    LoginButton loginButton;
    private CallbackManager callbackManager;
    TextView txt_name, txt_email, txt_birthday, txt_gender;
    ImageView img_profile;
    Button btn_logout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //   initialize facebook sdk
        FacebookSdk.sdkInitialize(MainActivity.this);
        setContentView(R.layout.activity_main);

//        PrintHashKey();

        loginButton = (LoginButton) findViewById(R.id.login_buttonFB);
        txt_name = (TextView) findViewById(R.id.txt_name);
        txt_email = (TextView) findViewById(R.id.txt_email);
        txt_gender = (TextView) findViewById(R.id.txt_gender);
        txt_birthday = (TextView) findViewById(R.id.txt_bDay);
        img_profile = (ImageView) findViewById(R.id.img_profile);
        btn_logout = (Button) findViewById(R.id.btn_logOut);

        loginButton.setReadPermissions(Arrays.asList("public_profile, email, user_birthday"));
        callbackManager = CallbackManager.Factory.create();

        // Callback registration
        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {

            @Override
            public void onSuccess(LoginResult loginResult) {
                GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        new GraphRequest.GraphJSONObjectCallback() {
                            @Override
                            public void onCompleted(JSONObject object, GraphResponse response) {
                                Log.v("Main", response.toString());
                                setProfileToView(object);
                            }
                        });
                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,name,email,gender, birthday");
                request.setParameters(parameters);
                request.executeAsync();
            }

            @Override
            public void onCancel() {
            }

            @Override
            public void onError(FacebookException exception) {
                Toast.makeText(MainActivity.this, "error to Login Facebook", Toast.LENGTH_SHORT).show();
            }
        });

        btn_logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LoginManager.getInstance().logOut();
                loginButton.setVisibility(View.VISIBLE);
                btn_logout.setVisibility(View.GONE);
                txt_name.setText("Name");
                txt_email.setText("Email Id");
                txt_gender.setText("Gender");
                txt_birthday.setText("Birthday");
                img_profile.setImageResource(R.drawable.user_pic);
            }
        });


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        callbackManager.onActivityResult(requestCode, resultCode, data);
    }


    private void setProfileToView(JSONObject jsonObject) {
        try {
            //   get details of the user
            String name = jsonObject.getString("name");
            String user_id = jsonObject.getString("id");
            String email = jsonObject.getString("email");
            String gender = jsonObject.getString("gender");
            String birthday = jsonObject.getString("birthday");
            String imgUrl = "https://graph.facebook.com/" + user_id + "/picture?type=large";
            Log.e("IMAGEURL", "" + imgUrl);
            Log.e("NAME", "" + name);

            //   set image url into imageview using picasso library
            Picasso.with(MainActivity.this)
                    .load(imgUrl)
                    .into(img_profile);

            //   assigning values to views
            txt_name.setText(name);
            txt_email.setText(email);
            txt_gender.setText(gender);
            txt_birthday.setText(birthday);
            loginButton.setVisibility(View.GONE);
            btn_logout.setVisibility(View.VISIBLE);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    public void PrintHashKey() {
        // Add this to print the key hash in log cat
        try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    "infinite.hss.com.loginandroidstudio",
                    PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.e("KEYHASH:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
        } catch (PackageManager.NameNotFoundException e) {

        } catch (NoSuchAlgorithmException e) {

        }
    }
}



  • Add facebook activity into your manifest file. Your Manifest.xml should look like this. 

File: Manifest.xml:


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="infinite.hss.com.loginandroidstudio">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/fb_id" />

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name="com.facebook.FacebookActivity"
            android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" />

    </application>

</manifest>


  • Now run your app and enjoy the output.

Output:





Thank you...



Comments