Friday 23 December 2016

Facebook login from android application

Facebook Login in Android Application


Facebook login provides a convenient way for people to log  into app without having to go through a signup process.

Using the latest version of  Facebook SDK's of android, it takes only a few minutes to add this feature to your android app.

In this blog, you will learn how to add a Facebook login into your android app and handle the event to log a user in using Facebook login.

 1. Register your app:

    All apps that use the Facebook SDK's must be registered with Facebook Account.

    - First login into Facebook Developer Page https://developers.facebook.com/


    - Click on login and Click a create a new app in the top right.

    - You will get a form that asks for the App's Display name, Contact email and Category.

    - Enter the required fields and click the "Create App ID". See below:



    - In the next screen, you are able to see your Application ID. Make a note of it. 

    - Because you will be need it later in your Facebook project. 

    - Next, Click on Settings (Left side on top):  Settings ---> Basic

    - Click on Add Platform, select Android.

    - Now Enter the Google Play Package Name of your app and the name of your Activity name.   

    - Key Hashes: After that to fill the key hash filed, open a command prompt window and run the key tool command to generate a  key hash using the Debug key store.
Debug Keystore:

keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | 
openssl sha1 -binary | openssl base64
 
Then it asks for password
The default password for the debug key store is android.
 
- The output of a command should be a 28 Characters string.Copy it.
- Go back to your browser, paste the string in to key hashes field.
 
 
- Make sure single sign on is set to yes and click the save changes button.
 
 
- Now, your app is registered with Facebook. 
 

2. Add Facebook SDK into your Project.

The Facebook SDK's is available on Maven Central. To use this repository, 
edit the build.gradle file in your project's app directory and add the following 
code to it. Before the list of dependencies.
 
See below, 
 
2.1. Create a New Project: 
 
 
 2.2. Click next, And select minimum SDk for your app
 
 
 2.3. Next, Select the activity
 
 
2.4.Click on Next, And finish button.
 

2.5. Now go to build.gradle(Module: app):


2.6. Add the following code.

   repositories {
        mavenCentral()
    }
 
2.7. Now you can add the Facebook SDK to your project as a compile dependency.
 
    - For that you need to go Facebook developer page and copy it
 
 Add compile 'com.facebook.android:facebook-android-sdk:[4,5)' to your build.gradle.
  


 
 2.8. Remember that the name of this class and packge name that it belongs should 
    be match the values you entered while registering your app with Facebook.


    - In your activities layout, create the Facebook login button
 

    activity_main.xml:
 
    <com.facebook.login.widget.LoginButton
    android:id="@+id/loginbutton"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/> 
 
   - In your MainActivity, declare the Facebook widget.
 
   private LoginButton loginButton;  
 
   In, oncreate method,
 
   loginButton = (LoginButton) findViewById(R.id.loginbutton);
 
 
  * Declare a CallbackManager on another field. The CallbackManager, as ts name 
    suggests is uses to manage the callbacks use in the app.
 
    - i.e. private CallbackManager callbackManager; 
 
  After that,
  - The SDk need to initialized before using any of its method. You can do so by 
  calling SDK Initialize. and passing the application context to it. 

  For this step create the Today Class and it needs to extends from Application Class.
 
 public class Today extends Application {
 
 @Override
    public void onCreate() {
        super.onCreate();
        FacebookSdk.sdkInitialize(getApplicationContext());
        AppEventsLogger.activateApp(this);
    }
  }  
 
 
 And, this call need to call in Manifest.xml 
 So, give the name in Application fied. See Below image: 
    
 - Now, Initialize your instance of callbackManager using the callbackManager.Facoty create method.
    
 - In your MainActivity, 
    
    callbackManager = CallbackManager.Factory.create();
 
    and
 
    loginButton = (LoginButton) findViewById(R.id.loginbutton);
 
After this step, for getting email from Facebook account we need to add permission 
on Callbackmanager.
 
So, we can write the code like this:
 
  loginButton.setReadPermissions(Arrays.asList("email")); 
    
 - Its the time to create the callback to handle the results of login attemtpts and 
   register it with the callbackManager.
    
 - Custom CallBack should implement FacebookCallback. The interface has methods to handle 
   each possible outcome of a login attempt.
    
 Now, implement the callbackManager method,
    
 loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {

            @Override
            public void onSuccess(LoginResult loginResult) {
                
            }

            @Override
            public void onCancel() {
                
            }

            @Override
            public void onError(FacebookException error) {
               
            }
        });
    
    
  - If the login attempt is successful, onSuccess is called.
  - If the user cancel the login attmept, onCanel is called.
  - If an error occurs, then onError is called.
 
- To register the customCallbacks, use the registerCallback method.
 
 So, if onSuccess is called, 
 
    - When the onSuccess() is called, a loginResult is passed as a parameter by using 
this code.
    
So, in this onSuccess(), implement the below code:
  
    
            @Override
            public void onSuccess(LoginResult loginResult) {

                System.out.println("onSuccess");

                String accessToken = loginResult.getAccessToken().getToken();
                Log.i("accessToken", accessToken);

                GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), 
new GraphRequest.GraphJSONObjectCallback() {

                    @Override
                    public void onCompleted(JSONObject object, GraphResponse response) {
                        Log.i("LoginActivity", response.toString());
                        // Get facebook data from login
                        Bundle bFacebookData = getFacebookData(object);
                    }
                });
                Bundle parameters = new Bundle();
                parameters.putString("fields", "id, first_name, last_name, email,gender, birthday, location");
                request.setParameters(parameters);
                request.executeAsync();
            } 
 
 
 After this step, create the getFacebookData() method.
 
  private Bundle getFacebookData(JSONObject object) {

        Bundle bundle = new Bundle();

        try {

            if (object.has("email"))

                bundle.putString("email", object.getString("email"));

            Log.e("email", object.getString("email"));

            goMainScreen();

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

        return bundle;
    }
 
 
 - By tapping the loginButton starts off a new Activity, which returns a result. To 
   receive and handle the result, override the onActivity result method of your activity.
  
 - And pass its parameter to the onActivity method of callbackmanager.
 
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }
 
 
- Now, finish the coding part, then add the Facebook ApplicationId into your 
 
   res -> values -> strings.xml
 
  <string name="facebook_app_id">your app ID</string> 
 

- Edit the Manifest.xml

 *  Add a uses-permission element to the manifest:

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

 *  Add a meta-data element to the application element:

   
    <meta-data 
         android:name="com.facebook.sdk.ApplicationId" 
         android:value="@string/facebook_app_id"/>
    
 * Add FacebookActivity to your AndroidManifest.xml: 

    <activity 
          android:name="com.facebook.FacebookActivity"
          android:configChanges=
                 "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
          android:label="@string/app_name" />
 
 
Here, its the Full code
 
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="wrap_content">

<com.facebook.login.widget.LoginButton
                android:id="@+id/loginbutton"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>

<RelativeLayout 
 
 
TodayApp.java:
 
public class Todayapp extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        FacebookSdk.sdkInitialize(getApplicationContext());
        AppEventsLogger.activateApp(this);
    }
}
 
 
MainActivity.java:
 
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;

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

import java.sql.Array;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

    private LoginButton loginButton;
    private CallbackManager callbackManager;
    private ProgressDialog progressDialog;

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

        callbackManager = CallbackManager.Factory.create();

        loginButton = (LoginButton) findViewById(R.id.loginbutton);

        loginButton.setReadPermissions(Arrays.asList("email"));

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

            @Override
            public void onSuccess(LoginResult loginResult) {

                System.out.println("onSuccess");
                progressDialog = new ProgressDialog(MainActivity.this);
                progressDialog.setMessage("Loading...");
                progressDialog.show();

                String accessToken = loginResult.getAccessToken().getToken();
                Log.i("accessToken", accessToken);

                GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
                new GraphRequest.GraphJSONObjectCallback() {

                    @Override
                    public void onCompleted(JSONObject object, GraphResponse response) {
                        Log.i("LoginActivity", response.toString());
                        // Get facebook data from login
                        Bundle bFacebookData = getFacebookData(object);
                    }
                });
                Bundle parameters = new Bundle();
                parameters.putString("fields", "id, first_name, last_name, email,gender, birthday, location");
                request.setParameters(parameters);
                request.executeAsync();
            }

            @Override
            public void onCancel() {
                Toast.makeText(getApplicationContext(), "login cancelled", Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onError(FacebookException error) {
                Toast.makeText(getApplicationContext(), "login Error", Toast.LENGTH_SHORT).show();
            }
        });

    }

    private Bundle getFacebookData(JSONObject object) {

        Bundle bundle = new Bundle();

        try {

            if (object.has("email"))

                bundle.putString("email", object.getString("email"));

            Log.e("email", object.getString("email"));

            goMainScreen();

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

        return bundle;
    }

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

Manifest.xml:
 

Add internet permission
 

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

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

    <application
        android:name=".Todayapp"
        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/facebook_app_id" />

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

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

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

</manifest>
 
 


strings.xml:
 
 <string name="facebook_app_id">Replace with your Facebook ApplicatioId</string>
 


 * Now, build and run. Your app is ready. Enjoy.