Saturday, 27 February 2016

Facebook Integration in Android Studio example | Android Facebook Integration

Helloooo warriors after a long time of planning finally in this post I am going to share with you  Facebook Integration in Android or you can say Login with Facebook in Android using Android studio.


No doubt there is hundreds of tutorial over internet for Facebook Integration in Android but Trust me this is going to be easiest one for you.

So Like Every tutorial I am going to make module of steps after that we will follow those steps to complete our project.

  1. Create a new Project in your Android Studio.
  2. Get Hash Key of your System for Facebook.
  3. Create New Project on Facebook Developer console.
  4. Add Facebook SDK in your build.gradle of app module .
  5. Add INTERNET permission,Facebook meta data and Facebook Activity in your manifest file.
  6. Add a TextView an ImageView and Facebook Login Button to activity_main.xml file
  7. Initialize Facebook SDK in MainActivity and Register Both button and TextView .
  8. Set Read permissions and register callBack to login Button .
  9. Execute Graph Request to get data of user inside onSuccess() method of Register callback.
 
1.Create a new Project in your Android Studio:-
Simplest step Open your Android studio Go to File>>New>>New project Select Empty Template and Leave everything as default.

2. Get Hash key of your system for Facebook Integration :- For this I already made a post How to generate hash key  so get hash key and save it anywhere.

3.Create New Project on  Facebook Developer console:- This step is also very simple just go to Facebook Developer and Login to your account Create New app like below picture


Click on Add a New App, a popup will launch with many options Select Android from them.on Next screen it will ask you to choose existing one or create new one since we are going to create new one so type name of your application you can name it anything it will appear on your login screen in android. type your app name and click on create new Facebook App ID like below picture.


after this a popup will launch just select a category for your app and click on Create Facebook ID. on Next screen scroll down the  page and you will see some thing like below picture.

Copy the string rounded with rectangle and paste it in your String file. this is your Facebook App ID.
Scroll down that page and you can see it will ask you to give Package name of your Android studio project and Name of Launcher Activity fill both and click on next like below picture.


  On Next It will ask you to add Hash key , So add your Hash key we have generated earlier and click on Next like below picture.




after this leave it and follow our next step.


4.Add Facebook SDK in your build.gradle of app module :-This step is very simple open your build.gradle of app module and below code under dependency. add one more library Picasso to show profile pic from url.


facebook gradle file:

compile 'com.facebook.android:facebook-android-sdk:4.+'

Picasso gradle file:

compile 'com.squareup.picasso:picasso:2.5.2'


5.Add INTERNET permission,Facebook meta data and Facebook Activity in your manifest file:- In this step we are going to add Internet permission, Facebook Activity and Facebook meta-data to our manifest file . Steps are very simple just open your manifest file and add below codes inside application tag.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<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"
    android:theme="@android:style/Theme.Translucent.NoTitleBar" />

Add Internet permission above application tag

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


6.Add a TextView an ImageView and Facebook Login Button to activity_main.xml file :-In this step open your activity_main.xml file and add a TextView an ImageView and Facebook login button to it here is my activity_main.xml file.


7.Initialize Facebook SDK in MainActivity and Register Both button and TextView:- Open your MainActivity.java file Initialize Facebook SDK before setContentView() method and Register Facebook login button,ImageView and TextView like below code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public class MainActivity extends AppCompatActivity {
    LoginButton loginButton;
    TextView tv_profile_name;
    ImageView iv_profile_pic;

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

        tv_profile_name = (TextView) findViewById(R.id.tv_profile_name);
        iv_profile_pic = (ImageView) findViewById(R.id.iv_profile_pic);
        loginButton = (LoginButton) findViewById(R.id.login_button);
        
    }

}

8.Set Read permissions and register callBack to login Button:- Since we are going to read data of user so we need to set Read permission in login Facebook Login Button and We need to add Register callBack to get Handle Response. here is the code for that.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
loginButton.setReadPermissions(Arrays.asList("public_profile, email, user_birthday, user_friends"));
        callbackManager = CallbackManager.Factory.create();

        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult){
			
			 }

            @Override
            public void onCancel() {

            }

            @Override
            public void onError(FacebookException error) {

            }
        });

9.Execute Graph Request to get data of user inside onSuccess() method of Register callback:- Inside onSuccess() method of Register callBack we are going to execute Graph Request to get user data , I am also setting user name to TextView and adding Image to ImageView using Picasso library in this code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
 GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        new GraphRequest.GraphJSONObjectCallback() {
                            @Override
                            public void onCompleted(JSONObject object, GraphResponse response) {


                                try {
                                    String email = object.getString("email");
                                    String birthday = object.getString("birthday");
                                    String id = object.getString("id");
                                    String name = object.getString("name");
                                    tv_profile_name.setText(name);

                                    
                                    String imageurl = "https://graph.facebook.com/" + id + "/picture?type=large";

                                    Picasso.with(MainActivity.this).load(imageurl).into(iv_profile_pic);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

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


/**
 * AccessTokenTracker to manage logout
 */
                accessTokenTracker = new AccessTokenTracker() {
                    @Override
                    protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken,
                                                               AccessToken currentAccessToken) {
                        if (currentAccessToken == null) {
                            tv_profile_name.setText("");
                            iv_profile_pic.setImageResource(R.drawable.maleicon);
                        }
                    }
                };

you can see accessTokenTracker in above code i am using this to remove Text from TextView and Image from ImageView on Logout. one Last thing we need to do is to adding callBackManager inside onActivityResult() like below code.


1
2
3
4
5
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }


And Finally we have completed this post. Here is my complete MainActivity.java file.


Still facing any problem feel free to comment below, If my post was helpful for you don't forget to share your experience by commenting  below because its motivate me to write new things.


0 comments:

Post a Comment