wake-up-neo.com

Gibt es ein Beispiel dafür, wie Sie sich mit Facebook SDK 4.0 in Android über den eigenen Button oder den Facebook Button anmelden können?

Gibt es ein Tutorial oder Beispiel, das zeigt, wie man sich mit einem eigenen Button mit Facebook SDK 4. in Android anmeldet? Ich komme nicht weiter und es ist schwierig, die Facebook-Entwicklerseite zu verstehen. Wie unten, wenn ich FBlogin button anrufe. Ich möchte überprüfen, ob der Benutzer sich nicht angemeldet hat oder ob ich den Zugang haben möchte Token, um Facebook-Profilinformationen und Nutzer-Likes zu erhalten.

FBlogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
             //Facebook login Code to get profile info and user likes  
        }
    });

Ich habe auch LoginButton Facebook ausprobiert.

  <com.facebook.login.widget.LoginButton
            Android:id="@+id/login_button"
            Android:layout_width="244dp"
            Android:layout_height="wrap_content"
            Android:layout_gravity="center_horizontal"
            Android:layout_marginTop="30dp"
            Android:layout_marginBottom="30dp" 

/>

Aber es zeigt Fehler in XML: -

Java.lang.NoClassDefFoundError: Could not initialize class com.facebook.login.widget.LoginButton
    at Sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at Sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.Java:62)
    at Sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.Java:45)
    at Java.lang.reflect.Constructor.newInstance(Constructor.Java:408)
    at org.jetbrains.Android.uipreview.ViewLoader.createNewInstance(ViewLoader.Java:413)
    at org.jetbrains.Android.uipreview.ViewLoader.loadView(ViewLoader.Java:105)
    at com.Android.tools.idea.rendering.LayoutlibCallback.loadView(LayoutlibCallback.Java:176)
    at Android.view.BridgeInflater.loadCustomView(BridgeInflater.Java:206)
    at Android.view.BridgeInflater.createViewFromTag(BridgeInflater.Java:131)
    at Android.view.LayoutInflater.rInflate_Original(LayoutInflater.Java:739)
    at Android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.Java:64)
    at Android.view.LayoutInflater.rInflate(LayoutInflater.Java:711)
    at Android.view.LayoutInflater.inflate(LayoutInflater.Java:489)
    at Android.view.LayoutInflater.inflate(LayoutInflater.Java:372)
    at com.Android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.Java:369)
    at com.Android.layoutlib.bridge.Bridge.createSession(Bridge.Java:326)
    at com.Android.ide.common.rendering.LayoutLibrary.createSession(LayoutLibrary.Java:350)
    at com.Android.tools.idea.rendering.RenderService$5.compute(RenderService.Java:708)
    at com.Android.tools.idea.rendering.RenderService$5.compute(RenderService.Java:697)
    at com.intellij.openapi.application.impl.ApplicationImpl.runReadAction(ApplicationImpl.Java:932)
    at com.Android.tools.idea.rendering.RenderService.createRenderSession(RenderService.Java:697)
    at com.Android.tools.idea.rendering.RenderService.render(RenderService.Java:816)
    at org.jetbrains.Android.uipreview.AndroidLayoutPreviewToolWindowManager.doRender(AndroidLayoutPreviewToolWindowManager.Java:646)
    at org.jetbrains.Android.uipreview.AndroidLayoutPreviewToolWindowManager.access$1700(AndroidLayoutPreviewToolWindowManager.Java:82)
    at org.jetbrains.Android.uipreview.AndroidLayoutPreviewToolWindowManager$7$1.run(AndroidLayoutPreviewToolWindowManager.Java:589)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$2.run(ProgressManagerImpl.Java:178)
    at com.intellij.openapi.progress.ProgressManager.executeProcessUnderProgress(ProgressManager.Java:209)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.Java:212)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.runProcess(ProgressManagerImpl.Java:171)
    at org.jetbrains.Android.uipreview.AndroidLayoutPreviewToolWindowManager$7.run(AndroidLayoutPreviewToolWindowManager.Java:584)
    at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.Java:320)
    at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.Java:310)
    at com.intellij.util.ui.update.MergingUpdateQueue$2.run(MergingUpdateQueue.Java:254)
    at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.Java:269)
    at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.Java:227)
    at com.intellij.util.ui.update.MergingUpdateQueue.run(MergingUpdateQueue.Java:217)
    at com.intellij.util.concurrency.QueueProcessor.runSafely(QueueProcessor.Java:238)
    at com.intellij.util.Alarm$Request$1.run(Alarm.Java:327)
    at Java.util.concurrent.Executors$RunnableAdapter.call(Executors.Java:511)
    at Java.util.concurrent.FutureTask.run(FutureTask.Java:266)
    at Java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.Java:1142)
    at Java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.Java:617)
    at Java.lang.Thread.run(Thread.Java:745)

Meine Aktivitätsklasse: -

protected void onCreate(Bundle savedInstanceState)  {
        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(getApplicationContext());
        setContentView(R.layout.activity_main);

Gibt es ein Beispiel/Tutorial, um sich mit Facebook SDK 4.0 anzumelden? Ich stecke in beide Richtungen fest. Bitte helfen Sie.

25

Das könnte dir helfen

// Custom button
private Button fbbutton;

// Creating Facebook CallbackManager Value
public static CallbackManager callbackmanager;

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Initialize SDK before setContentView(Layout ID)
    FacebookSdk.sdkInitialize(getApplicationContext());

    setContentView(R.layout.activity_main);

    // Initialize layout button
    fbbutton = (Button) findViewById(R.id.button2);

    fbbutton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // Call private method
            onFblogin();
        }
    });

}

// Private method to handle Facebook login and callback
private void onFblogin()
{
    callbackmanager = CallbackManager.Factory.create();

    // Set permissions 
    LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email","user_photos","public_profile"));

    LoginManager.getInstance().registerCallback(callbackmanager,
            new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult) {

                    System.out.println("Success");
                    GraphRequest.newMeRequest(
                            loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
                                @Override
                                public void onCompleted(JSONObject json, GraphResponse response) {
                                    if (response.getError() != null) {
                                        // handle error
                                        System.out.println("ERROR");
                                    } else {
                                        System.out.println("Success");
                                        try {

                                            String jsonresult = String.valueOf(json);
                                            System.out.println("JSON Result"+jsonresult);

                                            String str_email = json.getString("email");
                                            String str_id = json.getString("id");
                                            String str_firstname = json.getString("first_name");
                                            String str_lastname = json.getString("last_name");

                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }

                            }).executeAsync();

                }

                @Override
                public void onCancel() {
                    Log.d(TAG_CANCEL,"On cancel");
                }

                @Override
                public void onError(FacebookException error) { 
                    Log.d(TAG_ERROR,error.toString());
                }
    });
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    callbackmanager.onActivityResult(requestCode, resultCode, data);
}

Fügen Sie im Manifest Folgendes hinzu:

<application
    Android:allowBackup="true"
    Android:icon="@drawable/app_icon"
    Android:label="@string/app_name"
    Android:theme="@style/AppTheme" >
    .
    .
     <!-- [START Facebook] -->
    <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/facebook_app_id" />
    <!-- [END Facebook] -->
    .
    .
</application>
62
ManishSB

Die beste Lösung ist, sich mit LoginManager anzumelden. Hier ist, wie ich das geschafft habe (Klick wird mit ButterKnife gemacht):

 @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);        
    mCallbackManager = CallbackManager.Factory.create();
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    LoginManager.getInstance().registerCallback(mCallbackManager, this);
}

@OnClick(R.id.facebook_login_button)
@SuppressWarnings("unused")
public void loginWithFacebookAccount() {
    LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "email"));
}

@Override
public void onSuccess(LoginResult loginResult) {
    Bundle parameters = new Bundle();
    parameters.putString("fields", "id,name,last_name,link,email,picture");
    GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), (jsonObject, graphResponse) -> {
        String id = null;
        if (jsonObject != null) {
            try {
                id = jsonObject.getString("id");
            } catch (JSONException e) {
                e.printStackTrace();
            }                
        }
    });
    request.setParameters(parameters);
    request.executeAsync();
}

@Override
public void onCancel() {

}

@Override
public void onError(FacebookException e) {
}


@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        mCallbackManager.onActivityResult(requestCode, resultCode, data);           
    }
}

So habe ich es gemacht. Fragen Sie nur ;)

15
Pan Wrona
public class AuthWFacebookSDKFour extends Activity implements View.OnClickListener,FacebookCallback<LoginResult>   {

    List<String> permissionNeeds=Arrays.asList("user_photos","friends_photos", "email", "user_birthday", "user_friends");

    //facebook callbacks manager
    private CallbackManager cm;
    private LoginButton mFbLoginButton;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //init facebook sdk and 
        FacebookSdk.sdkInitialize(getApplicationContext());

        //instantiate callbacks manager
        mCallbackManager = CallbackManager.Factory.create();


        mFbLoginButton=(LoginButton)findViewById(R.id.FBBUTTONID);

        //set permissions mFbLoginButton.setReadPermissions(ApplicationContext.facebookPermissions);
        // register callback
        //means hey facebook after login call onActivityResult of **this**  
        mFbLoginButton.registerCallback(mCallbackManager, this);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        //manage login result
        mCallbackManager.onActivityResult(requestCode, resultCode, data);
    }


    @Override
    public void onSuccess(LoginResult loginResults) {


        //login ok  get access token 
        AccessToken.getActiveAccessToken();   

    }
    @Override
    public void onCancel() {

        Log.e(TAG(),"facebook login canceled");

    }


    @Override
    public void onError(FacebookException e) {



        Log.e(TAG(),"facebook login failed error");

    }






}

denken Sie daran, in das Manifest einzufügen

<activity
 Android:name="com.facebook.FacebookActivity"
 Android:label="@string/app_name"
 Android:theme="@Android:style/Theme.Translucent.NoTitleBar"
                />
5
dnocode

Für Facebook SDK Version 4.X In Ihrer Aktivität oder Ihrem Fragment (im Allgemeinen bei der onCreate () -Methode):

// Initialize Facebook Sdk before UI
    FacebookSdk.sdkInitialize(getApplicationContext());

    callbackManager = CallbackManager.Factory.create();
    loginButton = (LoginButton) findViewById(R.id.login_button);
    loginButton.setReadPermissions("user_friends");

    // Callback registration
    loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            // App code
            Log.v(TAG, "fblogin onSuccess");

        }

        @Override
        public void onCancel() {
            // App code
            Log.v(TAG, "fblogin onCancel");
        }

        @Override
        public void onError(FacebookException exception) {
            // App code
            Log.v(TAG, "fblogin onError");
        }
    });

Und vergessen Sie nicht, das Facebook-Aktivitätsergebnis an den Manager weiterzugeben:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    ...

    callbackManager.onActivityResult(requestCode, resultCode, data);
}
5
kyasar

Verwenden von Android facebook SDK 4.X Einloggen mit Facebook Standard Login Button

public class FbDefaultBtnLogin extends AppCompatActivity {

private CallbackManager callbackManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(getApplicationContext());
    setContentView(R.layout.activity_fb_default_btn_login);
    callbackManager = CallbackManager.Factory.create();
  //  LoginButton loginButton=(LoginButton)findViewById(R.id.login_button);


LoginManager.getInstance().logInWithReadPermissions(this,Arrays.asList("email","user_photos","public_profile"));
         LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {

            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onError(FacebookException e) {

            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }


<RelativeLayout 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"
    tools:context="com.jitendra.facebooklogin.FbDefaultBtnLogin">

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

</RelativeLayout>

Im Manifest: -

 <meta-data
        Android:name="com.facebook.sdk.ApplicationId"
        Android:value="@string/app_id" />
 <activity
        Android:name="com.facebook.FacebookActivity"
        Android:theme="@style/AppTheme" >
 </activity>
2
Jitendra Singh

hi check this tutorial: hier klicken

In diesem Tutorial können Sie latest Facebook SDK-Beispiel mit custom login und logout Taste Logik. enter image description here

1
nirav kalola