[android] using facebook sdk in Android studio

I'm following Facebook SDK for Android using Android Studio. When I run my application I'm getting the below mentioned warning.

Gradle: module 'facebook' won't be compiled. Unfortunately you can't have non-Gradle Java module and Android-Gradle module in one project.

How should I solve this?

I tried @Scott Barta's answer and get the following error message.

    A problem occurred configuring project ':App'.
> Failed to notify project evaluation listener.
   > A problem occurred configuring project ':libraries:facebook'.
      > Failed to notify project evaluation listener.
         > Could not resolve all dependencies for configuration ':libraries:facebook:_DebugCompile'.
            > Could not find any version that matches com.android.support:support-v4:+.
              Required by:
                  MyApplication2.libraries:facebook:unspecified

The answer is


When using git you can incorporate the newest facebook-android-sdk with ease.

  • Add facebook-android-sdk as submodule: git submodule add https://github.com/facebook/facebook-android-sdk.git
  • Add sdk as gradle project: edit settings.gradle and add line: include ':facebook-android-sdk:facebook'
  • Add sdk as dependency to module: edit build.gradle and add within dependencies block: compile project(':facebook-android-sdk:facebook')

Scott Barta's solution worked for me, except I had to add these to the dependencies of my main project build.gradle file:

compile files('libs/android-support-v4.jar')
compile project(':libraries:facebook')

Also worth mentioning, you need to make sure:

android {
    compileSdkVersion 18
    buildToolsVersion "18.1.1"

    defaultConfig {
        minSdkVersion 7
        targetSdkVersion 18
    }

Are the same in both build.gradle files...Once i did this it ran like a charm.


Facebook publishes the SDK on maven central :

Just add :

repositories {
    jcenter()       // IntelliJ main repo.
}

dependencies {
    compile 'com.facebook.android:facebook-android-sdk:+'
}

People using Android Studio 0.8.6 could do these:

  1. Download Facebook-android-sdk-xxx.zip & Unzip it
  2. Copy ONLY facebook dir under the Facebook-android-sdk-xxx dir into your project along with app/

    • ImAnApp/
      • |-- app/
      • |-- build/
      • |-- facebook/
  3. Now you should see Android Studio showing facebook as module

  4. Modify the build.gradle of facebook into this.
    • provided files('../libs/bolts.jar') to provided files('./libs/bolts.jar')
    • compileSdkVersion Integer.parseInt(project.ANDROID_BUILD_SDK_VERSION) to compileSdkVersion 20 or other version you defined in the app
    • buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION to buildToolsVersion '20.0.0'
    • minSdkVersion Integer.parseInt(project.ANDROID_BUILD_MIN_SDK_VERSION) to minSdkVersion 14
    • targetSdkVersion Integer.parseInt(project.ANDROID_BUILD_TARGET_SDK_VERSION) to targetSdkVersion 20

    apply plugin: 'android-library'

    dependencies {
        compile 'com.android.support:support-v4:19.1.+'
        provided files('./libs/bolts.jar')
    }

    android {
        compileSdkVersion 20
        buildToolsVersion '20.0.0'

        defaultConfig {
            minSdkVersion 14
            targetSdkVersion 20
        }

        lintOptions {
            abortOnError false
        }

        sourceSets {
            main {
                manifest.srcFile 'AndroidManifest.xml'
                java.srcDirs = ['src']
                res.srcDirs = ['res']
            }
        }
    }

Resync your gradle file & it should just work fine!


I have used facebook sdk 4.10.0 to integrate login in my android app. Tutorial I followed is :

facebook login 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.

add below in build.gradle(Module:app) file:

repositories {
        mavenCentral()
    }

and

 compile 'com.facebook.android:facebook-android-sdk:4.10.0'

now add below in AndroidManifest.xml file :

 <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="your app id from facebook developer console"/>

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

add following in activity_main.xml file :

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

    <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>

And in last add below in MainActivity.java file :

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.widget.TextView;

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.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;


public class MainActivity extends AppCompatActivity {

    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(fnm+" "+lnm+" \n"+mail+" \n"+gender+" \n"+fid+" \n"+birthday);

                            } 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);

        loginButton = (LoginButton) findViewById(R.id.btnfb);

        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();

    }

}

*Gradle Repository for the Facebook SDK.

dependencies {
    compile 'com.facebook.android:facebook-android-sdk:4.4.0'
}

Search for the latest version facebook sdk


Facebook has indeed added the SDK to the Maven Central repositories. To configure your project using the maven repo's instance, you'll need to do 2 things:

  1. In your projects top-level build.gradle file, add the Maven Central repositories. Mine looks like this:

    repositories {
        jcenter()       // This is the default repo
        mavenCentral()  //  This is the Maven Central repo
    }
    
  2. In the app-level build.grade file, add the Facebook sdk dependency:

    dependencies {
    
        compile 'com.facebook.android:facebook-android-sdk:4.5.0' // Adjust the version accordingly
        // All your other dependencies.
    }
    

You can also adjust the specific Facebook SDK version as well. For a list of available versions in the maven repository click this link.


I deployed Facebook Android SDK to Sonatype repository.

You can include this library as Gradle dependency:

repositories {
    maven {
        url 'https://oss.sonatype.org/content/groups/public'
    }
}

dependencies {
    compile 'com.shamanland:facebook-android-sdk:3.15.0-SNAPSHOT'
}

Original post here.


Create build.gradle file in facebook sdk project:

apply plugin: 'android-library'

dependencies {
    compile 'com.android.support:support-v4:18.0.+'
}

android {
    compileSdkVersion 8
    buildToolsVersion "19.0.0"

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }

        // Move the build types to build-types/<type>
        // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
        // This moves them out of them default location under src/<type>/... which would
        // conflict with src/ being used by the main source set.
        // Adding new build types or product flavors should be accompanied
        // by a similar customization.
        debug.setRoot('build-types/debug')
        release.setRoot('build-types/release')
    }
}

Then add include ':libs:facebook' equals <project_directory>/libs/facebook (path to library) in settings.gradle.


I fixed the

"Could not find property 'ANDROID_BUILD_SDK_VERSION' on project ':facebook'."

error on the build.gradle file, by adding in gradle.properties the values:

ANDROID_BUILD_TARGET_SDK_VERSION=21<br>
ANDROID_BUILD_MIN_SDK_VERSION=15<br>
ANDROID_BUILD_TOOLS_VERSION=21.1.2<br>
ANDROID_BUILD_SDK_VERSION=21<br>

Source: https://stackoverflow.com/a/21490651/2161698


using facebook sdk in android studio is quite simple , just add the following line in your gradle

  compile 'com.facebook.android:facebook-android-sdk:[4,5)'

and make sure that you have updated Android support repository , if not then update it using stand alone sdk manger


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to facebook

I am receiving warning in Facebook Application using PHP SDK React-Native: Application has not been registered error Can't Load URL: The domain of this URL isn't included in the app's domains Facebook OAuth "The domain of this URL isn't included in the app's domain" Facebook login message: "URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings." Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView` Open Facebook Page in Facebook App (if installed) on Android App not setup: This app is still in development mode IOS - How to segue programmatically using swift Get ALL User Friends Using Facebook Graph API - Android

Examples related to android-studio

A failure occurred while executing com.android.build.gradle.internal.tasks "Failed to install the following Android SDK packages as some licences have not been accepted" error Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util This version of Android Studio cannot open this project, please retry with Android Studio 3.4 or newer WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()' Flutter plugin not installed error;. When running flutter doctor ADB.exe is obsolete and has serious performance problems Android design support library for API 28 (P) not working Flutter command not found How to find the path of Flutter SDK

Examples related to facebook-android-sdk

Android Facebook 4.0 SDK How to get Email, Date of Birth and gender of User Facebook key hash does not match any stored key hashes using facebook sdk in Android studio How to programmatically log out from Facebook SDK 3.0 without using Facebook login/logout button? Openssl is not recognized as an internal or external command

Examples related to android-gradle-plugin

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()' Android Material and appcompat Manifest merger failed Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve Failed to resolve: com.google.firebase:firebase-core:16.0.1 com.google.android.gms:play-services-measurement-base is being requested by various other libraries Invoke-customs are only supported starting with android 0 --min-api 26 error: resource android:attr/fontVariationSettings not found Exception : AAPT2 error: check logs for details Could not resolve com.android.support:appcompat-v7:26.1.0 in Android Studio new project Failed to resolve: com.android.support:appcompat-v7:27.+ (Dependency Error)