using facebook sdk in Android studio
Asked Answered
C

12

104

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
Chalcidice answered 13/11, 2013 at 18:42 Comment(3)
Is your Android Support Repository installed in your SDK manager for the SDK you're using?Unicef
Nope. Is it mandatory?Chalcidice
Yes. That's the error message you're seeing. I know it's unintuitive; improving it is on our list. I'll update my answer to reflect the need for this.Unicef
U
249

NOTE

For Android Studio 0.5.5 and later, and with later versions of the Facebook SDK, this process is much simpler than what is documented below (which was written for earlier versions of both). If you're running the latest, all you need to do is this:

  1. Download the Facebook SDK from https://developers.facebook.com/docs/android/
  2. Unzip the archive
  3. In Android Studio 0.5.5 or later, choose "Import Module" from the File menu.
  4. In the wizard, set the source path of the module to import as the "facebook" directory inside the unpacked archive. (Note: If you choose the entire parent folder, it will bring in not only the library itself, but also all of the sample apps, each as a separate module. This may work but probably isn't what you want).
  5. Open project structure by Ctrl + Shift + Alt + S and then select dependencies tab. Click on + button and select Module Dependency. In the new window pop up select :facebook.
  6. You should be good to go.

Instructions for older Android Studio and older Facebook SDK

This applies to Android Studio 0.5.4 and earlier, and makes the most sense for versions of the Facebook SDK before Facebook offered Gradle build files for the distribution. I don't know in which version of the SDK they made that change.

Facebook's instructions under "Import the SDK into an Android Studio Project" on their https://developers.facebook.com/docs/getting-started/facebook-sdk-for-android-using-android-studio/3.0/ page are wrong for Gradle-based projects (i.e. your project was built using Android Studio's New Project wizard and/or has a build.gradle file for your application module). Follow these instructions instead:

  1. Create a libraries folder underneath your project's main directory. For example, if your project is HelloWorldProject, you would create a HelloWorldProject/libraries folder.

  2. Now copy the entire facebook directory from the SDK installation into the libraries folder you just created.

  3. Delete the libs folder in the facebook directory. If you like, delete the project.properties, build.xml, .classpath, and .project. files as well. You don't need them.

  4. Create a build.gradle file in the facebook directory with the following contents:

    buildscript {
        repositories {
            mavenCentral()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:0.6.+'
        }
    }
    
    apply plugin: 'android-library'
    
    dependencies {
        compile 'com.android.support:support-v4:+'
    }
    
    android {
        compileSdkVersion 17
        buildToolsVersion "19.0.0"
    
        defaultConfig {
            minSdkVersion 7
            targetSdkVersion 16
        }
    
        sourceSets {
            main {
                manifest.srcFile 'AndroidManifest.xml'
                java.srcDirs = ['src']
                resources.srcDirs = ['src']
                res.srcDirs = ['res']
            }
        }
    }
    

    Note that depending on when you're following these instructions compared to when this is written, you may need to adjust the classpath 'com.android.tools.build:gradle:0.6.+' line to reference a newer version of the Gradle plugin. Soon we will require version 0.7 or later. Try it out, and if you get an error that a newer version of the Gradle plugin is required, that's the line you have to edit.

  5. Make sure the Android Support Library in your SDK manager is installed.

  6. Edit your settings.gradle file in your application’s main directory and add this line:

    include ':libraries:facebook'
    
  7. If your project is already open in Android Studio, click the "Sync Project with Gradle Files" button in the toolbar. Once it's done, the facebook module should appear. enter image description here

  8. Open the Project Structure dialog. Choose Modules from the left-hand list, click on your application’s module, click on the Dependencies tab, and click on the + button to add a new dependency. enter image description here
  9. Choose “Module dependency”. It will bring up a dialog with a list of modules to choose from; select “:libraries:facebook”. enter image description here
  10. Click OK on all the dialogs. Android Studio will automatically resynchronize your project (making it unnecessary to click that "Sync Project with Gradle Files" button again) and pick up the new dependency. You should be good to go.
Unicef answered 13/11, 2013 at 18:42 Comment(22)
/libraries/facebook/build.gradle give me some errors. "Cannot resolve compileSdkVersion symbol". The same with compileSdkVersion symbol, manifest and others ...Adames
Can I add fb-sdk to an Android application or I can only add sdk to a new Android application?Adames
If you're having problems, please post them as a separate question and include the details of your error messages and build files.Unicef
Hi, I tried this and got an error in gradle task. I have updated the question with error details.Chalcidice
This worked for me, but I had to change the path to the facebook libraries grade project to be the absolute path, i.e. ":MyApp:libraries:facebook" in both the settings file and the build.grade file for my main appMet
Very good! This answer should be part of official Facebook SDK tutorial.Inextricable
Found no modules to depend on,Android Studio said.Chimere
I had to add include ':libraries:facebook' to my settings.gradle` and Sync Project with Gradle Files before I was able to get compile project(':libraries:facebook') to work right.Mayworm
I get an error that says \libraries\facebook\AndroidManifest.xml can not be found. I get this error after syncying with gradle. That file actually is not present in the folderSpurious
thank you @Scott for this incredibly fresh information on 0.5.5 plus. thank you!Stephi
This solution does not work for me. After selecting the facebook directory inside the facebook-android-sdk-3.16 directory, the wizard still says 'Select modules to import' :$. I use Android Studio (beta) 0.8.2. Any idea?Clumsy
Why can't they just make this thing straightforward for once?Ivanna
This works for me with a few additional steps: 1. Set facebook module as an explicit dependency of your main module in the module settings 2. Ensure the version of the bolts jar is the same for both the facebook and your main modules (usually mobile)Underquote
For the latest versions what you posted is essentially correct - you need to have the latest Android Support Library and Android Support Repository installed as well. Thanks for a great answer.Septuplet
If you choose the 'facebook' folder for the module import, then you need to copy the gradle.properties file from the parent folder into this 'facebook' folderAdrianadriana
The NOTE does not appear to be working for android studio version 0.8.14 and Facebook sdk v3.20. I get the error Gradle: module 'facebook' won't be compiled. Unfortunately you can't have non-Gradle Java module and Android-Gradle module in one projectMicroscopic
It gives to me 'Error:(26, 13) Gradle: error: package bolts does not exist'Someway
You don't need to do all this. Simply, just add the facebook dependency in your app's gradel build. Adjust the version accordingly. dependencies { compile 'com.facebook.android:facebook-android-sdk:3.23.+' }Chambray
did all things ... no any error... still unable to import com.facebook.SessionPhocis
It gives me Could not find property 'ANDROID_BUILD_SDK_VERSION' on project ':facebook'.Headgear
Error:(15, 0) Could not find property 'ANDROID_BUILD_SDK_VERSION' on project ':facebook'. <a href="openFile:/home/jaimin/AndroidStudioProjects/LatestFacebookIntegration/facebook/build.gradle">Open File</a>Pharisaism
when i click "Click on + button and select Module Dependency" --> there is no Module Dependency to selectTurro
G
107

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.

Griffon answered 12/11, 2014 at 15:26 Comment(5)
It is working for me. It is really the best way to add facebook api on Android Studio. ThanksPenner
This is the method on Facebook docs but it's not working. I have android studio 1.0 and sdk v 3.x.Dowager
Note you should specify an exact version number or at least a major, like 3.23.+. Facebook is not afraid to version the API rapidly and make breaking changes, which will cause build failures and non-repeatable builds.Debidebilitate
@GregEnnis - good input. I updated the answer slightly and added a comment in the code as well.Griffon
So, i do not have to import any external library and all? Just simple add the fb sdk in the gradle file??Chambray
C
17

Facebook publishes the SDK on maven central :

Just add :

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

dependencies {
    compile 'com.facebook.android:facebook-android-sdk:+'
}
Cephalalgia answered 9/11, 2014 at 15:53 Comment(2)
This is not right, you need mavenCentral() in the repositories section.Ninurta
jcenter include mavenCentralCephalalgia
Z
12

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.

Zellner answered 3/12, 2013 at 15:37 Comment(2)
I get an error when building: Project with path 'libraries:facebook' could not be found in root project ... Any ideas? (I have of course added the folder according to Scott Bs solution, even though I do NOT have a settings.gradle file?! (Project created in Android Studio)Donnettedonni
the compile project line needs to match your project directory structure. :libraries:facebook implies that your facebook library is in a folder called libraries within your root directoryHuonghupeh
M
6

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')
Musician answered 28/4, 2014 at 10:14 Comment(0)
E
4

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

    }

}
Eulogy answered 4/3, 2017 at 6:58 Comment(0)
B
3

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.

Bilberry answered 19/5, 2014 at 20:28 Comment(2)
This doesn't work anymore, your site is down. Killed my whole IDE.Stclair
Weird, I used sites that check if a site is down and even your homepage would not load.Stclair
F
2

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!

Frannie answered 21/8, 2014 at 6:16 Comment(0)
P
2

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://mcmap.net/q/205888/-importing-facebook-library-in-android-studio-could-not-find-property-39-android_build_sdk_version-39

Puerperal answered 12/1, 2015 at 19:3 Comment(0)
B
1

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.

Bawd answered 13/11, 2013 at 18:51 Comment(2)
I already did this. Still its showing the error. I think the error says facebook is non-gradle and so it cant be commpiled. But Im not sureChalcidice
Try build through console: ./gradlew clean assembleDebugBawd
I
1

*Gradle Repository for the Facebook SDK.

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

Search for the latest version facebook sdk

Indisposed answered 25/2, 2015 at 7:18 Comment(0)
M
0

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

Merell answered 3/5, 2016 at 11:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.