Facebook SDK 4. in Androidを使用して独自のボタンを使用してログインする方法を示すチュートリアルまたは例はありますか? Facebookの開発者サイトを使用して理解するのは難しいですFBloginボタンを呼び出すときは以下のように、ユーザーがログインしていない場合、またはログインしている場合はログインを確認しますFacebookのプロフィール情報とユーザーのいいね!を取得するトークン。
FBlogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Facebook login Code to get profile info and user likes
}
});
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"
/>
しかし、それは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)
私のアクティビティクラス:-
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
Facebookのsdk4.0を使用してログインする例/チュートリアルはありますか?私は両方の方法で立ち往生しています。助けてください。
これはあなたを助けるかもしれません
// 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);
}
マニフェストに以下を追加し、
<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>
最善の解決策は、LoginManagerを使用してログインすることです。これは私がこれをどのように管理したかです(クリックすると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);
}
}
これが私が作った方法です。お気軽にお尋ねください ;)
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");
}
}
マニフェストに挿入することを忘れないでください
<activity
Android:name="com.facebook.FacebookActivity"
Android:label="@string/app_name"
Android:theme="@Android:style/Theme.Translucent.NoTitleBar"
/>
Facebook SDKバージョン4.Xの場合、アクティビティまたはフラグメントで(通常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");
}
});
また、facebookのアクティビティ結果をマネージャーに渡すことも忘れないでください。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
...
callbackManager.onActivityResult(requestCode, resultCode, data);
}
Android facebook SDK 4.X facebookでのログインデフォルトのログインボタン
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>
マニフェスト内:-
<meta-data
Android:name="com.facebook.sdk.ApplicationId"
Android:value="@string/app_id" />
<activity
Android:name="com.facebook.FacebookActivity"
Android:theme="@style/AppTheme" >
</activity>
こんにちは、このチュートリアルを確認してください: ここをクリック
このチュートリアルでは、latestを使用したFacebook SDKの例を取得できますカスタムloginおよびlogoutbuttonロジック。