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
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
Thanks for the code. I want to access email ID too..
ReplyDeleteWhenever 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?
check code given above...for getting email id.
Deletegive me a source code please
DeleteThanks for the code Mohsin.
ReplyDeleteHI thanks for this code its very useful to me can you tel me how to logout after getting user profile information programatically
ReplyDeleteHi 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
ReplyDeleteThis comment has been removed by a blog administrator.
ReplyDeletehow to i get com.facebook.Profile class in android Eclipse...
ReplyDeleteplz share me link and ideas for getting com.facebook library........
go to facebook developer console, link is given above and than download android sdk.
DeleteThanks Mohsin!!
ReplyDeleteIn the manifest file it is showing that your main activity name is FacebookActivity (android:name="com.facebook.FacebookActivity"
ReplyDeleteandroid: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
This code not working with me...
ReplyDeleteWhen i use this code it closes app....
can anyone help??
Hey this code is not working with my app.
ReplyDeleteWhenever a user logins, the app crashes.
Please anyone can help????
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.
ReplyDeleteHey 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.
ReplyDeletewhere is LoginSuccess java file
ReplyDeletepublic class LoginSuccess extends Activity{
Delete@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 .
What will be in the intent.getStringExtra();
Deleteplease tell
How to get email from facebook SDK
ReplyDeleteuse this code
DeleteBundle parameters = new Bundle();
parameters.putString("fields", "id,name,email");
request.setParameters(parameters);
above code
request.executeAsync();
if you have above shared preference code for logout then please share with us,Sir !!
Deletehow to get user post ? plz help
ReplyDeletecan you share shared preference class please
ReplyDeleteWell Blogged !! Keep up the awesome work
ReplyDeletewhen getting email from fb then exception generate "no value for email"
ReplyDeletehow to solve this problem
when getting email from fb then exception generate "no value for email"
ReplyDeletehow to solve this problem
where is loginsuccess class in your code what fields we need to add in that layout xml file
ReplyDeleteCan you please share the shared preferences code that you used while logout ??
ReplyDeletewhen getting email from fb then exception generate "no value for email"
ReplyDeletehow to solve this problem
If user set email id to private on their Facebook account than you will not able to get user email.
Delete