简体   繁体   中英

Android Facebook SDK Login

i've got this page in my android app with 4 tabs and in one of this tabs there should be a login Facebook button, i followed Facebook tutorial but i can't add any of them scripts, and if i put some imports Facebook.. they are grey.. what should i do? Facebook is connected well in my build.gradle

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.webkit.WebView;


import static com.Andrea.material.sample.R.layout.page;

public class SampleFragment extends Fragment {

    private static final String ARG_POSITION = "position";
    private WebView myWebView;
    private String LOG_TAG = "AndroidWebViewActivity";



    private int position;

    public static SampleFragment newInstance(int position) {
        SampleFragment f = new SampleFragment();
        Bundle b = new Bundle();
        b.putInt(ARG_POSITION, position);
        f.setArguments(b);
        return f;
    }


    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        position = getArguments().getInt(ARG_POSITION);
        View rootView = inflater.inflate(page, container, false);

        ProgressBarCircular progressBarCircular = (ProgressBarCircular) rootView.findViewById(R.id.progress);
        FloatingActionButton fab = (FloatingActionButton) rootView.findViewById(R.id.fabButton);
        WebView webView = (WebView) rootView.findViewById(R.id.webView);

        fab.setDrawableIcon(getResources().getDrawable(R.drawable.plus));


        switch (position) {
            case 0:


                webView.loadUrl("http://www.google.com");



                break;
            case 1:

                webView.loadUrl("http://www.google.com");

                break;
            case 2:

                webView.loadUrl("http://www.google.com");

                break;
            case 3:

                webView.loadUrl("http://www.google.com");

                break;
        }

        return rootView;
    }
}

EDITS

ok, i followed some helps this is my activity now:

package com.Andrea.material.sample;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;

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.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;


import java.util.Arrays;

import static com.Andrea.material.sample.R.layout.page;


public class SampleFragment extends Fragment {

    private static final String ARG_POSITION = "position";
    private WebView myWebView;
    private String LOG_TAG = "AndroidWebViewActivity";

    FacebookSdk.sdkInitialize(getApplicationContext());

    private int position;

    public static SampleFragment newInstance(int position) {
        SampleFragment f = new SampleFragment();
        Bundle b = new Bundle();
        b.putInt(ARG_POSITION, position);
        f.setArguments(b);
        return f;
    }


    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        position = getArguments().getInt(ARG_POSITION);
        View rootView = inflater.inflate(page, container, false);

        ProgressBarCircular progressBarCircular = (ProgressBarCircular) rootView.findViewById(R.id.progress);
        FloatingActionButton fab = (FloatingActionButton) rootView.findViewById(R.id.fabButton);
        WebView webView = (WebView) rootView.findViewById(R.id.webView);

        fab.setDrawableIcon(getResources().getDrawable(R.drawable.plus));


        switch (position) {
            case 0:


                webView.loadUrl("http://www.google.com");



                break;
            case 1:

                webView.loadUrl("http://www.google.com");

                break;
            case 2:

                webView.loadUrl("http://www.google.com");

                break;
            case 3:

                //if the facebook profile is changed, below code block will be called
                profileTracker = new ProfileTracker() {
                    @Override
                    protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {

                        if(currentProfile != null){
                            fbUserId = currentProfile.getId();

                            if(!sharedPreferences.contains("UserName")){
                                editor.putString("UserName",currentProfile.getFirstName()+" "+currentProfile.getLastName());
                            }
                            if(!sharedPreferences.contains("FbId")){
                                editor.putString("FbId",currentProfile.getId());
                            }
                            if(!sharedPreferences.contains("ProfilePicture")){
                                editor.putString("ProfilePicture",currentProfile.getProfilePictureUri(100,100).toString());
                            }

                            editor.commit();
                        }
                    }
                };

                //when new fb user logged in , below code block will be called
                AccessTokenTracker accessTokenTracker = new AccessTokenTracker() {
                    @Override
                    protected void onCurrentAccessTokenChanged(AccessToken accessToken, AccessToken accessToken2) {
                        System.out.println("acesstoken trackercalled");
                    }
                };

                //set layout resource
                setContentView(R.layout.page);

                //fb login button
                loginButton = (LoginButton) findViewById(R.id.connectWithFbButton);

                //set fb permissions
                loginButton.setReadPermissions(Arrays.asList("public_profile,email"));

                //call the login callback manager
                callbackManager = CallbackManager.Factory.create();
                LoginManager.getInstance().registerCallback(callbackManager,
                        new FacebookCallback<LoginResult>() {
                            @Override
                            public void onSuccess(LoginResult loginResult) {

                                profile = Profile.getCurrentProfile();
                                if(profile != null){
                                    fbUserId = profile.getId();

                                    if(!sharedPreferences.contains("UserName")){
                                        editor.putString("UserName",profile.getFirstName()+" "+profile.getLastName());
                                    }
                                    if(!sharedPreferences.contains("FbId")){
                                        editor.putString("FbId",profile.getId());
                                    }
                                    if(!sharedPreferences.contains("ProfilePicture")){
                                        editor.putString("ProfilePicture",profile.getProfilePictureUri(20,20).toString());
                                    }
                                    editor.commit();
                                }

                                   //get here value of variables FBID and USERNAME to pass in
                                   //other webview
                            }

                            @Override
                            public void onCancel() {
                            }

                            @Override
                            public void onError(FacebookException e) {

                            }


                        });

                break;
        }

        return rootView;
    }

Android studio says me that : sdkInitialize profileTracker sharedPreferences fbUserId editor setContentView loginButton profile and callbackManager

"Cannot resolve symbol .(every names above)."

and also some errors as:

Error:(34, 30) error: <identifier> expected
Error:(34, 52) error: <identifier> expected
Error:(34, 53) error: ';' expected
Error:(34, 54) error: illegal start of type
Error:(34, 55) error: <identifier> expected
Error:(34, 56) error: ';' expected

EDIT2

No, Facebook sdks seems imported well... here is my app build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1"

    defaultConfig {
        applicationId "com.tekinarslan.material.sample"
        minSdkVersion 16
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:support-v4:21.0.0'
    compile 'com.android.support:appcompat-v7:21.0.0'
    compile 'com.android.tools.build:gradle:1.1.2'
    compile 'com.facebook.android:facebook-android-sdk:4.0.0'
}
repositories {
    mavenCentral()
}

In your layout you shouldn't specify as button from Facebook if you don't want to add custom behavior after pressing this button . It can look like this:

<com.facebook.widget.LoginButton
    android:id="@+id/fb_login_button"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="5dp"
    facebook:confirm_logout="false"
    facebook:fetch_user_info="true" />

and later in your case #3 you can catch action and specify additional work. I guess this is nice tutorial how to work with it. Also, facebook is pretty clear in his own tutorial . Since it is official, you should try it first.

UPDATE This line you should add before calling setContentView in Activity :

FacebookSdk.sdkInitialize(this);

Add this code to place where you want to execute it.

CallbackManager callbackManager = CallbackManager.Factory.create();

    LoginManager.getInstance().registerCallback(callbackManager,
            new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult) {
                    isFbUserLoggedIn = true;
                    final AccessToken accessToken = loginResult.getAccessToken();
                    GraphRequest request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
                                @Override
                                public void onCompleted(JSONObject JSONUser, GraphResponse graphResponse) {
                                    if (graphResponse.getError() != null) {
                                        showErrorDialog(graphResponse.getError().toString());
                                    } else {
                                        String firstName = JSONUser.optString(FinalValues.FIRST_NAME);
                                        String lastName = JSONUser.optString(FinalValues.LAST_NAME);
                                        String id = JSONUser.optString(FinalValues.ID);
                                    }
                                }

                            }

                    );
                    Bundle parameters = new Bundle();
                    parameters.putString("fields", "id, first_name, last_name");
                    request.setParameters(parameters);
                    request.executeAsync();
                }

                @Override
                public void onCancel() {
                }

                @Override
                public void onError(FacebookException exception) {
                    Log.d("LOG", exception.toString());
                }
            });
    LoginManager.getInstance().logInWithReadPermissions((Activity) activity, Arrays.asList("public_profile"));

This part you need to add to onActivityResult() method which you have to Override .

if(callbackManager != null){
        callbackManager.onActivityResult(requestCode, resultCode, data);
}

callbackManager must be global variable as you guessed.

Don't forget to update your Manifest.xml with FacebookActivity and set permission to use Internet:

<meta-data
    android:name="com.facebook.sdk.ApplicationId"
    android:value="@string/app_id"/> <!-- Get this one from developers.facebook -->
<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"/>

And:

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

Hope this is enough. Happy coding :)

Follow this answer . It's an analytical example of how to get going with facebook 4.0.+ API .

See my working code below.

Add FB button in layout:

    <com.facebook.login.widget.LoginButton
    android:id="@+id/connectWithFbButton"

    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:layout_centerInParent="true"
    android:text="connect with facebook"

    android:layout_marginTop="200dp"
    android:layout_marginLeft="30dp"
    android:layout_marginRight="30dp" />

Activity:

   //Initialize Facebook SDK
    FacebookSdk.sdkInitialize(getApplicationContext());

    //if the facebook profile is changed, below code block will be called
    profileTracker = new ProfileTracker() {
        @Override
        protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {

            if(currentProfile != null){
                fbUserId = currentProfile.getId();

                if(!sharedPreferences.contains("UserName")){
                    editor.putString("UserName",currentProfile.getFirstName()+" "+currentProfile.getLastName());
                }
                if(!sharedPreferences.contains("FbId")){
                    editor.putString("FbId",currentProfile.getId());
                }
                if(!sharedPreferences.contains("ProfilePicture")){
                    editor.putString("ProfilePicture",currentProfile.getProfilePictureUri(100,100).toString());
                }

                editor.commit();
            }
        }
    };

    //when new fb user logged in , below code block will be called
    AccessTokenTracker accessTokenTracker = new AccessTokenTracker() {
        @Override
        protected void onCurrentAccessTokenChanged(AccessToken accessToken, AccessToken accessToken2) {
            System.out.println("acesstoken trackercalled");
        }
    };

          //set layout resource
    setContentView(R.layout.activity_login);

    //fb login button
    loginButton = (LoginButton) findViewById(R.id.connectWithFbButton);

    //set fb permissions
    loginButton.setReadPermissions(Arrays.asList("public_profile,email"));

    //call the login callback manager
    callbackManager = CallbackManager.Factory.create();
    LoginManager.getInstance().registerCallback(callbackManager,
            new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult) {

                    profile = Profile.getCurrentProfile();
                    if(profile != null){
                        fbUserId = profile.getId();

                        if(!sharedPreferences.contains("UserName")){
                            editor.putString("UserName",profile.getFirstName()+" "+profile.getLastName());
                        }
                        if(!sharedPreferences.contains("FbId")){
                            editor.putString("FbId",profile.getId());
                        }
                        if(!sharedPreferences.contains("ProfilePicture")){
                            editor.putString("ProfilePicture",profile.getProfilePictureUri(20,20).toString());
                        }
                        editor.commit();
                    }



                    goToNewActivity();
                }

                @Override
                public void onCancel() {
                }

                @Override
                public void onError(FacebookException e) {

                }


            });

AndroidManifest.xml

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM