Header Ads

Android Facebook SDK Login and get user information in Android Studio

Learn easy steps to login with Facebook Android SDK and save user details. Mostly apps use Facebook login feature to get user info without giving a long form to fill up data and save them. Here is simple steps:-
Android Facebook Login


Facebook Steps


Go to Facebook developer console:- Facebook Developer Console and create an app, enter all description, images, banner in App Details and put it into live mode in Status & Review . After that go to Dashboard and click on Getting Started button and select Android and than follow the given steps there. Download Facebook Android SDK, generate hash, put all info there. Some basic questions:-

Question:- How to generate hash?



public void getHashCode() {

    try {
        PackageInfo info = getPackageManager().getPackageInfo("com.the360lifechange",                
         PackageManager.GET_SIGNATURES);        
         for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");            
            md.update(signature.toByteArray());            
            Log.wtf("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));        
       }
    } catch (PackageManager.NameNotFoundException e) {

    } catch (NoSuchAlgorithmException e) {

    }

}


Project Steps


Extract downloaded Facebook SDK file and you will find a "facebook" project inside the whole package. Now open android studio and import it as a module(import as a module only "facbook" project not complete projects).

Open facebook project module and define a string "facebook_app_id" in string.xml file.

 name="facebook_app_id">625178694184501

change it with your app id. now change manifest file of Facebook project:-


 xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.facebook">

     android:minSdkVersion="9"/>

     android:name="android.permission.INTERNET"/>

    
         android:name="com.facebook.FacebookActivity"
            android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:theme="@android:style/Theme.Translucent.NoTitleBar"
            android:label="@string/facebook_app_name" />

         android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>

    

You have done from facebook project module and now move to your main project. Go to file -> project structure -> dependency -> add facebook.

Now open your layout file and add a button for facbook login and assign id name "bt_facebook" than use below code in your activity for Facebook login and user details:-

package com.exampe.facebooklogin; //your project name

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.facebook.AccessToken;
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.Profile;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;

import java.util.Arrays;

public class FacebookLogin extends ActionBarActivity {

    //For facebook
    private CallbackManager callbackManager;

    private Button facebook_button;
    ProgressDialog progress;
    private String facebook_id,f_name, m_name, l_name, gender, profile_image, full_name, email_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            getSupportActionBar().hide();
        }catch (NullPointerException e){

        }
        setContentView(R.layout.activity_facebook_login);

        facebook_button=(Button)findViewById(R.id.bt_facebook);

        progress=new ProgressDialog(FacebookLogin.this);
        progress.setMessage(getResources().getString(R.string.please_wait_facebooklogin));
        progress.setIndeterminate(false);
        progress.setCancelable(false);

        facebook_id=f_name= m_name= l_name= gender= profile_image= full_name= email_id="";

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

        //register callback object for facebook result
        LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                progress.show();
                Profile profile = Profile.getCurrentProfile();
                if (profile != null) {
                    facebook_id=profile.getId();
                    f_name=profile.getFirstName();
                    m_name=profile.getMiddleName();
                    l_name=profile.getLastName();
                    full_name=profile.getName();
                    profile_image=profile.getProfilePictureUri(400, 400).toString();
                }
                //Toast.makeText(FacebookLogin.this,"Wait...",Toast.LENGTH_SHORT).show();
                GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
                        new GraphRequest.GraphJSONObjectCallback() {
                            @Override
                            public void onCompleted(JSONObject object, GraphResponse response) {
                                try {
                                    email_id=object.getString("email");
                                    gender=object.getString("gender");
         //Start new activity or use this info in your project.
                                    Intent i=new Intent(FacebookLogin.this, LoginSuccess.class);
                                    i.putExtra("type","facebook");
                                    i.putExtra("facebook_id",facebook_id);
                                    i.putExtra("f_name",f_name);
                                    i.putExtra("m_name",m_name);
                                    i.putExtra("l_name",l_name);
                                    i.putExtra("full_name",full_name);
                                    i.putExtra("profile_image",profile_image);
                                    i.putExtra("email_id",email_id);
                                    i.putExtra("gender",gender);

                                    progress.dismiss();
                                    startActivity(i);
                                    finish();
                                } catch (JSONException e) {
                                    // TODO Auto-generated catch block
                                    //  e.printStackTrace();
                                }

                            }

                        });

                request.executeAsync();
            }

            @Override
            public void onCancel() {
                Toast.makeText(FacebookLogin.this,getResources().getString(R.string.login_canceled_facebooklogin),Toast.LENGTH_SHORT).show();
                progress.dismiss();
            }

            @Override
            public void onError(FacebookException error) {
                Toast.makeText(FacebookLogin.this,getResources().getString(R.string.login_failed_facebooklogin),Toast.LENGTH_SHORT).show();
                progress.dismiss();
            }
        });

        //facebook button click
        facebook_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LoginManager.getInstance().logInWithReadPermissions(FacebookLogin.this, Arrays.asList("public_profile", "user_friends", "email"));
            }
        });
    }

    //for facebook callback result.
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }
}

In this post, I used custom button for login, you all can use official Facebook button. Don't forget to share this post. If you have any question regarding this post than feel free to comment.

No comments:

Powered by Blogger.