1

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()
}
Jack_usti
  • 99
  • 1
  • 11
  • in your code I don't see anything related to `Facebook API`, If you say `import`s are grey so you did install, but never use this `class`. What you're trying to achieve? – Yurets Apr 28 '15 at 18:34
  • @Yurets i'm trying to get in my last tab : "case 3" a button with Facebook login, please help me. – Jack_usti Apr 28 '15 at 18:54
  • no panic. You want to customize behavior after clicking or simply launch facebook `LoginActivity`? – Yurets Apr 28 '15 at 18:59
  • if possible when click Facebook button i want to open Facebook App, login and after get the userid and the username, i need them to pass to my web view. in IoS programming is all easier ^^ @Yurets – Jack_usti Apr 28 '15 at 19:07
  • possible duplicate of [login facebook getlocation and email](http://stackoverflow.com/questions/29605236/login-facebook-getlocation-and-email) – Menelaos Kotsollaris Apr 28 '15 at 19:23

3 Answers3

0

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

Yurets
  • 3,999
  • 17
  • 54
  • 74
  • the problem is when i import `import com.facebook.Session; 12 import com.facebook.SessionState; 13 import com.facebook.UiLifecycleHelper; 14 import com.facebook.model.GraphUser; 15 import com.facebook.widget.LoginButton; 16 import com.facebook.widget.LoginButton.UserInfoChangedCallback;` it doesn't work.. @Yurets – Jack_usti Apr 28 '15 at 19:13
  • i followed Deepika example but it doesn't work anyway, see my edits please @Yurets – Jack_usti Apr 29 '15 at 14:19
  • if all of characters cannot be resolved you did not install `facebook-sdk` properly. Add this line to your `build.gradle` in `dependencies`, `compile 'com.facebook.android:facebook-android-sdk:4.0.0'`press "sync now" which will appear in top-right corner and try again. – Yurets Apr 29 '15 at 14:23
  • Facebook seems imported well.. see my edits2 @Yurets – Jack_usti Apr 29 '15 at 16:15
0

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

Community
  • 1
  • 1
Menelaos Kotsollaris
  • 5,776
  • 9
  • 54
  • 68
0

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" />
Deepika
  • 516
  • 4
  • 6