Existe-t-il un tutoriel ou un exemple montrant comment se connecter en utilisant son propre bouton en utilisant Facebook SDK 4. in Android? Je ne vais nulle part et j'utilise le site des développeurs Facebook, il est difficile à comprendre.Comme ci-dessous lors de l'appel FBlogin bouton Je veux vérifier go for login si l'utilisateur ne s'est pas connecté ou si connecté je veux l'accès jeton pour obtenir les informations de profil facebook et les goûts des utilisateurs.
FBlogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Facebook login Code to get profile info and user likes
}
});
J'ai également essayé loginButton Facebook.
<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"
/>
Mais il montre une erreur en 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)
Ma classe d'activité: -
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
Y a-t-il un exemple/tutoriel pour se connecter en utilisant facebook sdk4.0? Je suis coincé dans les deux sens. Veuillez aider.
Cela pourrait vous aider
// 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);
}
Dans le manifeste, ajoutez ce qui suit,
<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>
La meilleure solution consiste à vous connecter à l'aide de LoginManager. Voici comment j'ai géré cela (au clic est fait avec ButterKnife):
@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);
}
}
Voilà donc comment je l'ai fait. N'hésitez pas à demander ;)
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");
}
}
n'oubliez pas d'insérer dans le manifeste
<activity
Android:name="com.facebook.FacebookActivity"
Android:label="@string/app_name"
Android:theme="@Android:style/Theme.Translucent.NoTitleBar"
/>
Pour Facebook SDK version 4.X, dans votre activité ou fragment (généralement sur la méthode onCreate ()):
// 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");
}
});
Et n'oubliez pas de transmettre le résultat de l'activité Facebook au manager:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
...
callbackManager.onActivityResult(requestCode, resultCode, data);
}
Utilisation de Android facebook SDK 4.X Login with Facebook Default 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>
Dans 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>
salut consultez ce tutoriel: cliquez ici
Dans ce tutoriel, vous pouvez obtenir dernier Exemple de SDK Facebook avec personnalisé login et déconnexion logique du bouton .