Pages

Wednesday, 9 July 2014

Android Facebook SDK integration with user details 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?
Answer:- Download openssl.exe from official site or from code.google.com (I downloaded from official site)and unzip it. Open command prompt and type below command to generate hash:

keytool -exportcert -alias mykey -keystore %HOMEPATH%\.android\debug.keystore | "C:\openssl\openssl.exe" sha1 -binary | "C:\openssl\openssl.exe" base64

cmd will ask password than generate hash and in my case, openssl.exe was in C:\openssl\ directory so change it accordingly. Copy your app id and now you have all done from Facebook side.

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.

<string name="facebook_app_id">625178694184501</string>

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

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

    <uses-sdk android:minSdkVersion="9"/>

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

    <application>
        <activity 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" />

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

    </application>
</manifest>

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");
                                    String profile_name=object.getString("name");
                                    long fb_id=object.getLong("id"); //use this for logout
         //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);
    }
}

To logout from Facebook:-

private void logoutFromFacebook(){
        try {
            if (AccessToken.getCurrentAccessToken() == null) {
                return; // already logged out
            }
            long fb_id=sp.getFacebookId(); //get fb id from sharedprefrences
            GraphRequest graphRequest=new GraphRequest(AccessToken.getCurrentAccessToken(), "/ "+fb_id+"/permissions/", null,
                    HttpMethod.DELETE, new GraphRequest.Callback() {
                        @Override
                        public void onCompleted(GraphResponse graphResponse) {
                            LoginManager.getInstance().logOut();
                        }
            });

            graphRequest.executeAsync();
        }catch(Exception ex) {
            ex.printStackTrace();
        }
    }

To get current Access Token:-

AccessToken.getCurrentAccessToken().getToken();

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.

Related Tutorials:-

Add Google AdMob Ads in Android App & Earn Money

Advance Android Google Map 2 Tutorial with Examples - Part 1

Start Working on Linphone Android

Easy Reader: Gesture controlled TextView (With Pinch to Zoom)

Android Twitter Fabric SDK Integration with user details in Android Studio

30 comments:

  1. Thanks for the code. I want to access email ID too..
    Whenever i try user.getProperty("email"); my application crashes. I add email permission in List PERMISSIONS = Arrays.asList("publish_actions","email");
    Can you tell what i m doing wrong?

    ReplyDelete
    Replies
    1. check code given above...for getting email id.

      Delete
    2. give me a source code please

      Delete
  2. Thanks for the code Mohsin.

    ReplyDelete
  3. HI thanks for this code its very useful to me can you tel me how to logout after getting user profile information programatically

    ReplyDelete
  4. Hi please tel me why i am getting null values for profile user information while first time login to facebook using the above,please tel me i have tried alot but didn't find any solution

    ReplyDelete
  5. This comment has been removed by a blog administrator.

    ReplyDelete
  6. how to i get com.facebook.Profile class in android Eclipse...

    plz share me link and ideas for getting com.facebook library........

    ReplyDelete
    Replies
    1. go to facebook developer console, link is given above and than download android sdk.

      Delete
  7. In the manifest file it is showing that your main activity name is FacebookActivity (android:name="com.facebook.FacebookActivity"
    android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation") but in the main class file or in the main activity it is FacebookLogin......what the reson behind that? plz tell me in details

    ReplyDelete
  8. This code not working with me...
    When i use this code it closes app....

    can anyone help??

    ReplyDelete
  9. Hey this code is not working with my app.
    Whenever a user logins, the app crashes.

    Please anyone can help????

    ReplyDelete
  10. Hey I have problem in this code regards Call back manager and facebook sdk does not import and give me error.I have add Facebook sdk in my project but still it give error...Give me a solution.

    ReplyDelete
  11. Hey I have problem in this code regards Call back manager and facebook sdk does not import and give me error.I have add Facebook sdk in my project but still it give error...Give me a solution.

    ReplyDelete
  12. where is LoginSuccess java file

    ReplyDelete
    Replies
    1. public class LoginSuccess extends Activity{
      @Override
      protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.loginsuccess);
      }
      }


      create and put what your want or call the class your want to call , when it has logged in .

      Delete
    2. What will be in the intent.getStringExtra();
      please tell

      Delete
  13. How to get email from facebook SDK

    ReplyDelete
    Replies
    1. use this code
      Bundle parameters = new Bundle();
      parameters.putString("fields", "id,name,email");
      request.setParameters(parameters);

      above code
      request.executeAsync();

      Delete
    2. if you have above shared preference code for logout then please share with us,Sir !!

      Delete
  14. how to get user post ? plz help

    ReplyDelete
  15. Anonymous3:34 pm

    can you share shared preference class please

    ReplyDelete
  16. Well Blogged !! Keep up the awesome work

    ReplyDelete
  17. when getting email from fb then exception generate "no value for email"
    how to solve this problem

    ReplyDelete
  18. when getting email from fb then exception generate "no value for email"
    how to solve this problem

    ReplyDelete
  19. where is loginsuccess class in your code what fields we need to add in that layout xml file

    ReplyDelete
  20. Can you please share the shared preferences code that you used while logout ??

    ReplyDelete
  21. when getting email from fb then exception generate "no value for email"
    how to solve this problem

    ReplyDelete
    Replies
    1. If user set email id to private on their Facebook account than you will not able to get user email.

      Delete

Back to Top