Skip to main content

Facebook login using sdk 4.0 easy way to implement and get profile info

we need to add  this two libraries in gradle file

gradle.app 

dependencies {
    
    compile 'com.facebook.android:facebook-android-sdk:4.+'
    compile 'com.squareup.picasso:picasso:2.3.2'}

First gradle for the facebook integration and other is for downloading image.

Create activity_login.xml file and paste this code.

activity_login.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.arpit.facebooklogin.LoginActivity">

    <com.facebook.login.widget.LoginButton
        android:id="@+id/login_button"
        android:layout_width="wrap_content"
        android:layout_height="90dp"
        android:textSize="18sp"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />



</RelativeLayout>

Then create LoginActivity.java and paste this code.

LoginActivity.java

   import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
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.appevents.AppEventsLogger;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;

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

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

public class LoginActivity extends AppCompatActivity {

    private CallbackManager callbackManager;
    private LoginButton fbLoginButton;
    static String Name, Email, ProfilePic, DOB;

    // flag for Internet connection status
    Boolean isInternetPresent = false;

    // Connection detector class
    ConnectionDetector cd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        FacebookSdk.sdkInitialize(getApplicationContext());
        callbackManager = CallbackManager.Factory.create();

        //You need this method to be used only once to configure
        //your key hash in your App Console at
        // developers.facebook.com/apps

        showHashKey(LoginActivity.this);
        // creating connection detector class instance
        cd = new ConnectionDetector(getApplicationContext());
        // get Internet status
        isInternetPresent = cd.isConnectingToInternet();

        setContentView(R.layout.activity_login);
        fbLoginButton = (LoginButton) findViewById(R.id.login_button);
        fbLoginButton.setReadPermissions(Arrays.asList("public_profile, email, user_birthday, user_friends"));


            fbLoginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {

                @Override
                public void onSuccess(LoginResult loginResult) {

                    // App code
                    GraphRequest request = GraphRequest.newMeRequest(
                            loginResult.getAccessToken(),
                            new GraphRequest.GraphJSONObjectCallback() {
                                @Override
                                public void onCompleted(
                                        JSONObject object,
                                        GraphResponse response) {
                                    // Application code
                                    Log.v("Profile ---------   ", response.toString());

                                    try {
                                        Name = object.getString("name");
                                        Email = object.getString("email");
                                        DOB = object.getString("birthday");
                                        Log.v("Email = ", " " + Email);
                                        //                                    Toast.makeText(getApplicationContext(), "Name " + Name, Toast.LENGTH_LONG).show();

                                        Toast.makeText(LoginActivity.this, "Login Successful!", Toast.LENGTH_LONG).show();

                                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                        startActivity(intent);

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


                                }
                            });

                    Bundle parameters = new Bundle();
                    parameters.putString("fields", "id,name,email,gender, birthday");
                    request.setParameters(parameters);
                    request.executeAsync();

                    System.out.println("Facebook Login Successful!");
                    System.out.println("Logged in user Details : ");
                    System.out.println("--------------------------");
                    System.out.println("User ID  : " + loginResult.getAccessToken().getUserId());
                    System.out.println("Authentication Token : " + loginResult.getAccessToken().getToken());

                }


                @Override
                public void onCancel() {
                    Toast.makeText(LoginActivity.this, "Login cancelled by user!", Toast.LENGTH_LONG).show();
                    System.out.println("Facebook Login failed!!");

                }

                @Override
                public void onError(FacebookException e) {
                    Toast.makeText(LoginActivity.this, "Login unsuccessful!", Toast.LENGTH_LONG).show();
                    System.out.println("Facebook Login failed!! because of " + e.getCause().toString());
                }
            });

    }

    @Override
    protected void onResume() {
        super.onResume();

        // Logs 'install' and 'app activate' App Events.
        AppEventsLogger.activateApp(this);
    }

    @Override
    protected void onPause() {
        super.onPause();

        // Logs 'app deactivate' App Event.
        AppEventsLogger.deactivateApp(this);
    }

    public static void showHashKey(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    "com.example.arpit.facebooklogin", PackageManager.GET_SIGNATURES); //Your            package name here
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.i("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
        } catch (PackageManager.NameNotFoundException e) {
        } catch (NoSuchAlgorithmException e) {
        }
    }

    @Override
    protected void onActivityResult(int reqCode, int resCode, Intent i) {
        callbackManager.onActivityResult(reqCode, resCode, i);
    }

}

then get the profile info in this screen activity_main.xml

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:elevation="9dp">

        <TextView
            android:id="@+id/Name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="30dp"
            android:text="Name : "
            android:textColor="@color/colorPrimaryDark"
            android:textStyle="bold"
            android:layout_marginTop="20dp"
            android:layout_below="@+id/imageView"
            android:textAppearance="?android:attr/textAppearanceMedium"
            />

        <TextView
            android:id="@+id/Email"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Email : "
            android:textColor="@color/colorPrimaryDark"
            android:textStyle="bold"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:layout_below="@+id/Name"
            android:layout_alignLeft="@+id/Name"
            android:layout_alignStart="@+id/Name"
            android:layout_marginTop="15dp" />

        <TextView
            android:id="@+id/Dob"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dp"
            android:textColor="@color/colorPrimaryDark"
            android:text="D.O.B : "
            android:textStyle="bold"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:layout_below="@+id/Email"
            android:layout_alignLeft="@+id/Email"
            android:layout_alignStart="@+id/Email" />


        <Button
            android:id="@+id/btn_Logout"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:background="@color/com_facebook_blue"
            android:textColor="@color/cardview_light_background"
            android:textSize="18sp"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="141dp"
            android:text="Logout" />


        <ImageView
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:layout_marginTop="15dp"
            android:background="@drawable/com_facebook_profile_picture_blank_square"
            android:id="@+id/imageView"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true" />

    </RelativeLayout>

</RelativeLayout>

copy this code into your MainActivity.java.

MainActivity.java

public class MainActivity extends AppCompatActivity {

    TextView Name,Email,DOB;
    ImageView ProfilePic;
    Button Logout;
    String ImgURL;


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

        Name=(TextView)findViewById(R.id.Name);
        Email=(TextView)findViewById(R.id.Email);
        DOB=(TextView)findViewById(R.id.Dob);
        Logout = (Button)findViewById(R.id.btn_Logout);
        ProfilePic=(ImageView)findViewById(R.id.imageView);

        Name.setText("Name : "+LoginActivity.Name);
        Email.setText("Email : "+LoginActivity.Email);
        DOB.setText("DOB : "+LoginActivity.DOB);

        //For the profile picture        try{
            Profile profile = Profile.getCurrentProfile();
            ImgURL = "https://graph.facebook.com/"+profile.getId()+"/picture?type=large";

            Picasso.with(MainActivity.this)
                    .load("" + ImgURL)
                    .into(ProfilePic);
        }catch (Exception e){

            e.printStackTrace();
        }

        Logout.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {

                Toast.makeText(MainActivity.this, "Logout clicked...", Toast.LENGTH_SHORT).show();
                //For Logout Facebook SDK                LoginManager.getInstance().logOut();
                Intent intent =new Intent(MainActivity.this,LoginActivity.class);
                startActivity(intent);
            }
        });

    }

    @Override    protected void onStart() {
        super.onStart();

    }

    @Override    protected void onResume() {
        super.onResume();

        // Logs 'install' and 'app activate' App Events.        AppEventsLogger.activateApp(this);
    }

    @Override    protected void onPause() {
        super.onPause();

        // Logs 'app deactivate' App Event.        AppEventsLogger.deactivateApp(this);
    }

    @Override    public void onBackPressed() {
//        super.onBackPressed();    }
}

This is my gradle file compare to your gradle file

gradle.app

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.example.arpit.facebooklogin"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
repositories {
    mavenCentral()
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.facebook.android:facebook-android-sdk:4.+'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
    compile 'com.squareup.picasso:picasso:2.3.2'
}


Note: Don't forget to change your facebook_app_id (path=res>values>string.xml) after download

Comments

Popular posts from this blog

web2apk

http://web2apk.com/create.aspx Create App   Intro   About   Changes   MalWare ?   Contact   Privacy Useful Links Bluetooth Mini Keyboards Android Mini PC Reset Android URL App Title Icon or

how to retrieve image from sqlite database in android and display in listview

 Android platform provides several ways to store data in our application. 1. SQLite database 2. SharedPreferences etc For our post, we will only work with SQLite database. First and foremost, we need to understand what an SQLite database is? SQLite database  is an open source SQL database that stores data to a text file on a device. It executes SQL Commands to perform a set of functions, that is, create, read, update and delete operations. On my previous post, I showed how to  store data in SQLite database from edit text, retrieve and populate it in a listview . For this post, I will show the SQLite CRUD operations with images from gallery and text from EditText. We need to understand this; images are stored in SQLite database as BLOB data type. A BLOB is a large binary object that can hold a variable amount of data.  Note, we can only store images in the database as BLOB data type. We need to convert our image path to a bitmap then to bytes. Also

Android Bar Chart Using MpAndroidChart Library Tutorial

https://www.numetriclabz.com/android-bar-chart-using-mpandroidchart-library-tutorial/ Android Bar Chart Using MpAndroidChart Library Tutorial Objective In this tutorial we learn how to implement Bar Chart using MpAndroidChart Library in your Android App. Download Source Code       Step 1 Contents ·        1  Introduction ·        2  Creating Bar chart o    2.1  Create a new Project o    2.2  Adding library in Project o    2.3  Create Layout o    2.4  To Plot Bar Chart §   2.4.1  Initialize the graph id §   2.4.2  Creating a Dataset §   2.4.3  Defining X-axis labels §   2.4.4  Set the data §   2.4.5  Add the description to the chart §   2.4.6  Run your App §   2.4.7  Set the color §   2.4.8  Adding Animations o    2.5  To plot grouped bar chart §   2.5.1  Creating Dataset o    2.6  Get the best of Android plus exclusive deals and freebies in your inbox!