X
    Categories: Advanced

Android Facebook Based Login Tutorial Part – 2

 

Facebook login :

In Continuation to the previous tutorial on facebook login, in this part of the tutorial we will start coding in android studio. So we will start by designing a facebook based login button.

To make it easier i have divided tutorial into two parts first part is complete backend integration where as second part deals with android app coding.

Generally when you require a user login or authentication in your app we make use of these third party login integrations which will make it easier for user to login much easily.

In the app level coding we have java and kotlin so as to make it easy for understanding i am providing both the code’s and you may use any one of them to attain same output.

For testing the login functionality you may create test users in facebook console and use them to login in development mode.

 

Can Visit this link for first part here

 

 

Facebook login full code :

Here we are going to see the detailed tutorial on facebook login in both java and kotlin.

 

Java Code :

We will initialize Facebook SDK in onCreate

facebookSDKInitialize();
protected void facebookSDKInitialize() {

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

Here are three phases when you click login button.

  1. on success the non Success(LoginResult login_result) is executed.
  2. on cancel then onCancel() is executed.
  3. on cancel then onError(FacebookException exception) is executed.

 

login_button.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
    @Override
    public void onSuccess(LoginResult login_result) {
        Intent intent = new Intent(MainActivity.this,Home.class);
        startActivity(intent);

    }

    @Override
    public void onCancel() {
        // code for cancellation
    }

    @Override
    public void onError(FacebookException exception) {
        //  code to handle error
    }
});

Create MainActivity.java

 

Providing the full code for login integration using facebook.

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;

/**
 * Created by Abhishek on 6/22/2016.
 */

public class MainActivity extends AppCompatActivity {
 CallbackManager callbackManager;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 facebookSDKInitialize();
 setContentView(R.layout.activity_main);
 LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
 loginButton.setReadPermissions("email");
 getLoginDetails(loginButton);
 }
 /*
 Initialize the facebook sdk.
 And then callback manager will handle the login responses.
 */
 protected void facebookSDKInitialize() {

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

 /*
 Register a callback function with LoginButton to respond to the login result.
 */

 protected void getLoginDetails(LoginButton login_button){

 // Callback registration
 login_button.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
 @Override
 public void onSuccess(LoginResult login_result) {
 Intent intent = new Intent(MainActivity.this,Home.class);
 startActivity(intent);

 }

 @Override
 public void onCancel() {
 // code for cancellation
 }

 @Override
 public void onError(FacebookException exception) {
 // code to handle error
 }
 });
 }

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

 @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_main, 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.

 return super.onOptionsItemSelected(item);
 }

 @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);
 }
}

 

Creating activity_main.xml

 

Now adding a login button in xml file

 

<?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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    tools:context=".MainActivity"
    android:gravity="center">

    <com.facebook.login.widget.LoginButton
        android:id="@+id/login_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"/>

</RelativeLayout>

 

Creating Home.java

 

After successful login we will move to another screen called Home Activity

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.facebook.login.LoginManager;

/**
 * Created by Abhishek on 6/22/2016.
 */
public class Home extends AppCompatActivity {

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

        (findViewById(R.id.logout)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                LoginManager.getInstance().logOut();
                Intent intent = new Intent(Home.this,MainActivity.class);
                startActivity(intent);
            }
        });
    }
}

 

Creating home.xml

 

After successful login user can logout by clicking logout button in home screen.

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

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

</LinearLayout>

 

Kotlin Code :

Here i am providing the facebook intergration using kotlin code.

package com.abhi.facebook_login

import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.facebook.*
import com.facebook.login.LoginManager
import com.facebook.login.LoginResult
import kotlinx.android.synthetic.main.activity_main.*
import org.json.JSONException
import java.net.URL
import java.util.*


class MainActivity : AppCompatActivity() {

   lateinit var callbackManager : CallbackManager

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        callbackManager = CallbackManager.Factory.create()

        LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email,public_profile"));


        LoginManager.getInstance().registerCallback(callbackManager,
            object : FacebookCallback<LoginResult?> {
                override fun onSuccess(loginResult: LoginResult?) {
                    // App code
                   // Log.d("Access Token"," - "+loginResult?.accessToken?.token)

                    loadProfile(loginResult!!.accessToken)
                }

                override fun onCancel() {
                    // App code
                }

                override fun onError(exception: FacebookException) {
                    // App code
                }

            })

        val accessToken = AccessToken.getCurrentAccessToken()


        val isLoggedIn = accessToken != null && !accessToken.isExpired


    }



    override fun onActivityResult(
        requestCode: Int,
        resultCode: Int,
        data: Intent?
    ) {
        callbackManager.onActivityResult(requestCode, resultCode, data)
        super.onActivityResult(requestCode, resultCode, data)
    }


     fun loadProfile(newAccessToken: AccessToken) {
        val request =
            GraphRequest.newMeRequest(
                newAccessToken
            ) { `object`, response ->
                try {

                    val id = `object`.getString("id")
                    val first_name = `object`.getString("first_name")
                    val last_name = `object`.getString("last_name")
                    val email = `object`.getString("email")

                    Log.d("AccessToken",""+first_name)

                    txtId.setText(id)
                    txtName.setText(first_name+"   "+last_name)
                    txtEmail.setText(email)


                } catch (e: JSONException) {
                    e.printStackTrace()
                }
            }
        val parameters = Bundle()
        parameters.putString("fields", "first_name,last_name,email,id")
        request.parameters = parameters
        request.executeAsync()
    }


}


 

Facebook login output :

This screen below depicts the implementation of android facebook login.

 

 

 

If you have any query in this tutorial on facebook login  do let us know in comment section below. If you like this tutorial do like and share us for more interesting updates.

abhishek:
Related Post

This website uses cookies.