I am trying to login with facebook using android sdk 4.7. I have tried the following link http://www.theappguruz.com/blog/android-facebook-integration-tutorial http://www.androidhive.info/2012/03/android-facebook-connect-tutorial/
-
The best example for facebook login : http://www.demoadda.com/demo/android/login-with-facebook_108 – Kishan Dhamat May 04 '17 at 08:10
5 Answers
This code works for me, try it out and check that you are using facebook sdk 4.7
package com.kushal.facebooklogin;
import java.util.Arrays;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.facebook.*;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
public class FacebookLogin extends FragmentActivity
{
private TextView tvfirst_name, tvlast_namee, tvfull_name, tvEmail;
private CallbackManager callbackManager;
LoginButton login_button;
String email,name,first_name,last_name;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(this.getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.main);
tvfirst_name = (TextView) findViewById(R.id.first_name);
tvlast_namee = (TextView) findViewById(R.id.last_name);
tvfull_name = (TextView) findViewById(R.id.full_name);
tvEmail = (TextView) findViewById(R.id.email);
login_button = (LoginButton) findViewById(R.id.login_button);
login_button.setReadPermissions(Arrays.asList("public_profile","email"));
login_button.registerCallback(callbackManager, new FacebookCallback<LoginResult>()
{
@Override
public void onSuccess(LoginResult loginResult)
{
login_button.setVisibility(View.GONE);
GraphRequest graphRequest = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback()
{
@Override
public void onCompleted(JSONObject object, GraphResponse response)
{
Log.d("JSON", ""+response.getJSONObject().toString());
try
{
email = object.getString("email");
name = object.getString("name");
first_name = object.optString("first_name");
last_name = object.optString("last_name");
tvEmail.setText(email);
tvfirst_name.setText(first_name);
tvlast_namee.setText(last_name);
tvfull_name.setText(name);
LoginManager.getInstance().logOut();
}
catch (JSONException e)
{
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,first_name,last_name,email");
graphRequest.setParameters(parameters);
graphRequest.executeAsync();
}
@Override
public void onCancel()
{
}
@Override
public void onError(FacebookException exception)
{
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
the xml design is as follow
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:facebook="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFF"
android:gravity="center"
android:orientation="vertical" >
<com.facebook.login.widget.LoginButton
android:id="@+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:orientation="vertical" >
<TextView
android:id="@+id/first_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:textSize="18sp" />
<TextView
android:id="@+id/last_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:textSize="18sp" />
<TextView
android:id="@+id/full_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:textSize="18sp" />
<TextView
android:id="@+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:textSize="18sp" />
</LinearLayout>
</LinearLayout>
the mainefest file is as follow:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.kushal.facebooklogin"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:icon="@drawable/icon"
android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar" >
<activity
android:name=".FacebookLogin"
android:label="@string/app_name"
android:windowSoftInputMode="adjustResize" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<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" />
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="@string/app_id" />
</application>
</manifest>
- 795
- 1
- 5
- 23
-
To get the profile picture: `"http://graph.facebook.com/" + loginResult.getAccessToken().getUserId() + "/picture?type=large";` – Amiraslan Jun 23 '17 at 22:50
You can use the Facebook Android SDK. Here you have explained in the documentation how to build a Facebook Login to your app.
It says:
The simplest way to add Facebook Login to your app is to add
LoginButtonfrom the SDK. This is a custom view implementation of aButton. You can use this button in your app to implement Facebook Login.Add the Login Button
Add the button to your layout XML file with the full class name, com.facebook.widget.LoginButton:
<com.facebook.login.widget.LoginButton android:id="@+id/login_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="30dp" android:layout_marginBottom="30dp" />Then set up the button in your UI by adding it to a fragment and update your activity to use your fragment.
You can customize the properties of Login button and register a callback in your
onCreateView()method.Properties you can customize includes
LoginBehavior,DefaultAudience,ToolTipPopup.Style and permissions on theLoginButton. For example:@Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.splash, container, false); loginButton = (LoginButton) view.findViewById(R.id.login_button); loginButton.setReadPermissions("user_friends"); // If using in a fragment loginButton.setFragment(this); // Other app specific specialization // Callback registration loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { // App code } @Override public void onCancel() { // App code } @Override public void onError(FacebookException exception) { // App code } }); }If you use the
LoginButtonin a fragment, you need to set the fragment on the button as shown by callingsetFragment.You then need to call
FacebookSdk.initializeto initialize the SDK, and then callCallbackManager.Factory.createto create a callback manager to handle login responses. Here's an example of adding the callback in a fragment:public class MainActivity extends FragmentActivity { CallbackManager callbackManager; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FacebookSdk.sdkInitialize(getApplicationContext()); callbackManager = CallbackManager.Factory.create(); LoginButton loginButton = (LoginButton) view.findViewById(R.id.usersettings_fragment_login_button); loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { ... }); }Finally you should call
callbackManager.onActivityResultto pass the login results to theLoginManagerviacallbackManager.Register a Callback
To respond to a login result, you need to register a callback with either
LoginManagerorLoginButton. If you register the callback withLoginButton, don't need to register the callback on Login manager.You add the callback to your activity or fragment's
onCreate()method:@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FacebookSdk.sdkInitialize(this.getApplicationContext()); callbackManager = CallbackManager.Factory.create(); LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { // App code } @Override public void onCancel() { // App code } @Override public void onError(FacebookException exception) { // App code } }); }If login succeeds, the
LoginResultparameter has the newAccessToken, and the most recently granted or declined permissions.You don't need a
registerCallbackfor login to succeed, you can choose to follow current access token changes with theAccessTokenTrackerclass described below.Then in
onActivityResult()forward the login results to thecallbackManagercreated inonCreate():@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); callbackManager.onActivityResult(requestCode, resultCode, data); }Every activity and fragment that you integrate with the FacebookSDK Login or Share should forward
onActivityResultto thecallbackManager.To learn more about getting additional permissions see:
Managing Permissions, Android, Permissions with Facebook Login
- 5,396
- 1
- 26
- 50
I have used facebook sdk 4.10.0 to integrate login in my android app. Tutorial I followed is :
Facebook login integration android studio.
You will be able to get first name, last name, email, gender , facebook id and birth date from facebbok.
Above tutorial also explains how to create app in facebook developer console through video.
Gradle.build
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
applicationId "com.demonuts.fblogin"
minSdkVersion 16
targetSdkVersion 22
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
repositories {
mavenCentral()
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.facebook.android:facebook-android-sdk:4.10.0'
compile 'com.github.androidquery:androidquery:0.26.9'
}
Source code for activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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:orientation="vertical"
tools:context="com.demonuts.fblogin.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000"
android:layout_marginLeft="10dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="@+id/text"/>
<ImageView
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:id="@+id/ivpic"
android:src="@mipmap/ic_launcher"/>
<com.facebook.login.widget.LoginButton
android:id="@+id/btnfb"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" /> </LinearLayout>
Code for MainActivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import com.androidquery.AQuery;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
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.ProfileTracker;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
private AQuery aQuery;
private ImageView ivpic;
private TextView tvdetails;
private CallbackManager callbackManager;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker profileTracker;
private LoginButton loginButton;
private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.v("LoginActivity", response.toString());
// Application code
try {
Log.d("tttttt",object.getString("id"));
String birthday="";
if(object.has("birthday")){
birthday = object.getString("birthday"); // 01/31/1980 format
}
String fnm = object.getString("first_name");
String lnm = object.getString("last_name");
String mail = object.getString("email");
String gender = object.getString("gender");
String fid = object.getString("id");
tvdetails.setText("Name: "+fnm+" "+lnm+" \n"+"Email: "+mail+" \n"+"Gender: "+gender+" \n"+"ID: "+fid+" \n"+"Birth Date: "+birthday);
aQuery.id(ivpic).image("https://graph.facebook.com/" + fid + "/picture?type=large");
//https://graph.facebook.com/143990709444026/picture?type=large
Log.d("aswwww","https://graph.facebook.com/"+fid+"/picture?type=large");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, first_name, last_name, email, gender, birthday, location");
request.setParameters(parameters);
request.executeAsync();
}
@Override
public void onCancel() {
}
@Override
public void onError(FacebookException error) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(this);
setContentView(R.layout.activity_main);
tvdetails = (TextView) findViewById(R.id.text);
ivpic = (ImageView) findViewById(R.id.ivpic);
loginButton = (LoginButton) findViewById(R.id.btnfb);
aQuery = new AQuery(this);
callbackManager = CallbackManager.Factory.create();
accessTokenTracker= new AccessTokenTracker() {
@Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
}
};
profileTracker = new ProfileTracker() {
@Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
}
};
accessTokenTracker.startTracking();
profileTracker.startTracking();
loginButton.setReadPermissions(Arrays.asList("public_profile", "email", "user_birthday", "user_friends"));
loginButton.registerCallback(callbackManager, callback);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onStop() {
super.onStop();
accessTokenTracker.stopTracking();
profileTracker.stopTracking();
}
@Override
public void onResume() {
super.onResume();
Profile profile = Profile.getCurrentProfile();
}
}
- 4,593
- 1
- 33
- 33
Check this simple facebook login Library:
https://github.com/sromku/android-simple-facebook
Here is the link to my uploaded demo for simple facebook login with custom button: http://www.demoadda.com/demo/android/login-with-facebook_108
Its the simplest way to implement the facebook login in android application.
You can add the button like this :
<TextView
android:id="@+id/btnFb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:background="@null"
android:gravity="center"
android:text="Login with Facebook"
android:textColor="@color/white" />
And in gradle File you can add:
compile 'com.sromku:simple-fb:4.1.1'
Please check.
- 3,746
- 2
- 26
- 36
FACEBOOK LOGIN STEPBYSTEP
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
printHashKey();
meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="@string/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" />
btnFacebook.setReadPermissions("public_profile","email");
btnFacebook.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
String facebook_email;
String name;
String profilePicUrl;
private ProfileTracker mProfileTracker;
@Override
public void onSuccess(LoginResult loginResult) {
Log.e("facabook","Step1");
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.e("LoginActivity", response.toString());
// Application code
try {
facebook_email = object.getString("email");
name=object.getString("name");
if (object.has("picture")) {
profilePicUrl = object.getJSONObject("picture").getJSONObject("data").getString("url");
// set profile image to imageview using Picasso or Native methods
}
} catch (JSONException e) {
e.printStackTrace();
}
if(Profile.getCurrentProfile() == null) {
mProfileTracker = new ProfileTracker() {
@Override
protected void onCurrentProfileChanged(Profile profile, Profile profile2) {
// profile2 is the new profile
Log.e("facebook - profile", profile2.getFirstName());
facebookLogin(facebook_email,name,profilePicUrl,Constant.DUMMY_PASSWORD);
mProfileTracker.stopTracking();
}
};
mProfileTracker.startTracking();
} else {
facebookLogin(facebook_email,name,profilePicUrl,Constant.DUMMY_PASSWORD);
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,picture.type(large)");
request.setParameters(parameters);
request.executeAsync();
}
@Override
public void onCancel() {
Log.e("facebook - onCancel", "cancelled");
}
@Override
public void onError(FacebookException e) {
Log.e("facebook - onError", e.getMessage());
Toast.makeText(SignInActivity.this,e.getMessage(),Toast.LENGTH_LONG).show();
}
});
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e("Request Code", requestCode + "===========");
if(requestCode==64206)
{
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
- 61
- 1
- 3
