我正在尝试在我的应用程序中实现facebook登录,但每当我启动我的应用程序时它都会崩溃。我正关注facebook developer网站。这是我的代码。
MainActivity.java
package com.algor7.samplelogin;
...
public class MainActivity extends Activity {
private LoginButton loginButton;
private CallbackManager callbackManager;
private AccessTokenTracker accessTokenTracker;
private AccessToken accessToken;
private ProfileTracker profileTracker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FacebookSdk.sdkInitialize(this.getApplicationContext());
callbackManager = CallbackManager.Factory.create();
accessTokenTracker = new AccessTokenTracker() {
@Override
protected void onCurrentAccessTokenChanged(
AccessToken oldAccessToken,
AccessToken currentAccessToken) {
// Set the access token using
// currentAccessToken when it's loaded or set.
}
};
// If the access token is available already assign it.
accessToken = AccessToken.getCurrentAccessToken();
profileTracker = new ProfileTracker() {
@Override
protected void onCurrentProfileChanged(
Profile oldProfile,
Profile currentProfile) {
// App code
}
};
loginButton.findViewById(R.id.login_button);
loginButton.setReadPermissions("email");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
// App code
}
@Override
public void onCancel() {
// App code
}
@Override
public void onError(FacebookException exception) {
// App code
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onDestroy() {
super.onDestroy();
accessTokenTracker.stopTracking();
profileTracker.stopTracking();
}
}
activity_main.xml中
<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"
android:gravity="center"
tools:context=".MainActivity">
<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>
的strings.xml
<resources>
<string name="app_name">SampleLogin</string>
<string name="facebook_app_id">4932151xxxxxxxx</string>
<string name="fb_login_protocol_scheme">fb4932151xxxxxxxx</string>
的AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.algor7.samplelogin" >
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.facebook.CustomTabActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="@string/fb_login_protocol_scheme" />
</intent-filter>
</activity>
<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" />
</application>
的build.gradle(项目:)
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.3.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
的build.gradle(模块:应用)
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
applicationId "com.algor7.samplelogin"
minSdkVersion 17
targetSdkVersion 23
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:appcompat-v7:24.0.0-alpha2'
compile 'com.facebook.android:facebook-android-sdk:[4,5)'
}
Logcat:
--------- beginning of crash
05-16 15:28:57.915 2478-2478/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.algor7.samplelogin, PID: 2478
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.algor7.samplelogin/com.algor7.samplelogin.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View com.facebook.login.widget.LoginButton.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View com.facebook.login.widget.LoginButton.findViewById(int)' on a null object reference
at com.algor7.samplelogin.MainActivity.onCreate(MainActivity.java:54)
at android.app.Activity.performCreate(Activity.java:6251)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
请帮我解决这个问题。提前谢谢!
答案 0 :(得分:0)
Try to do like this:
public class MainActivity extends Activity {
private CallbackManager mfbCallbackManager;
private LoginManager mfbLoginManager;
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout. activity_main);
mfbCallbackManager = CallbackManager.Factory.create();
mfbLoginManager = LoginManager.getInstance();
mfbLoginManager.registerCallback(mfbCallbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult fbLoginResult) {
GraphRequest fbGraphRequest = GraphRequest.newMeRequest(fbLoginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
Profile fbProfile = Profile.getCurrentProfile();
String email = null, gender = null, dob = null;
try {
email = object.getString("email");
gender = object.getString("gender");
dob = object.getString("birthday");
} catch (JSONException e) {
AppUtil.writeLog(TAG, e.getMessage());
}
mCustomer = new Customer();
try {
mCustomer.setCustFbId(fbProfile.getId());
mCustomer.setCustName(fbProfile.getName());
mCustomer.setCustFbiImageUrl(fbProfile.getProfilePictureUri(Constants.FB_PROFILE_PIC_WIDTH, Constants.FB_PROFILE_PIC_HEIGHT).toString());
mCustomer.setCustEmail(email);
mCustomer.setCustGender(gender);
mCustomer.setCustType(Constants.CUSTOMER_ROLE);
mCustomer.setCustDob(dob);
} catch (NullPointerException e) {
AppUtil.writeLog(TAG, e.getMessage());
}
loginWithFb();
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "gender, age_range, email, birthday");
fbGraphRequest.setParameters(parameters);
fbGraphRequest.executeAsync();
}
private void loginWithFb() {
EndpointInterface apiService = AppUtil.getRetrofitInstance().create(EndpointInterface.class);
Call<LoginResp> call = apiService.loinWithFacebook(
mCustomer.getCustFbId(),
mCustomer.getCustName(),
mCustomer.getCustType(),
mCustomer.getCustFbiImageUrl(),
mCustomer.getCustEmail(),
mCustomer.getCustDob(),
mCustomer.getCustGender(),
mAppPreferences.getString(Constants.SETTINGS_GCM_ID, ""),
IS_PUSH_ENABLED
);
final ProgressDialog dialog;
dialog = new ProgressDialog(LoginActivity.this);
dialog.setMessage(getString(R.string.fb_login_wait_msg));
dialog.setCanceledOnTouchOutside(false);
dialog.show();
call.enqueue(new Callback<LoginResp>() {
@Override
public void onResponse(Call<LoginResp> call, Response<LoginResp> response) {
mCustomer.setCustId(response.body().getCustId());
mCustomer.setIsNew(response.body().getIsNew());
SharedPreferences.Editor preferenceEditor = mAppPreferences.edit();
preferenceEditor.putString(Constants.SETTINGS_OBJ_CUSTOMER, new Gson().toJson(mCustomer));
preferenceEditor.putBoolean(Constants.SETTINGS_IS_LOGGED_IN, true);
preferenceEditor.apply();
dialog.dismiss();
startActivity(new Intent(LoginActivity.this, HomeActivity.class));
finish();
}
@Override
public void onFailure(Call<LoginResp> call, Throwable t) {
dialog.dismiss();
Toast.makeText(LoginActivity.this, R.string.server_error + t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
答案 1 :(得分:0)
而不是
loginButton.findViewById(R.id.login_button);
使用
findViewById(R.id.login_button);
问题是
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View com.facebook.login.widget.LoginButton.findViewById(int)' on a null object reference
at com.algor7.samplelogin.MainActivity.onCreate(MainActivity.java:54)
loginButton
是null
的含义是什么。您正尝试在login_button
内找到尚未初始化的视图loginButton
。你必须在活动中找到视图。
答案 2 :(得分:-1)
您应该在片段中而不是在活动中进行登录。如果我没错,facebook doc会要求您将登录按钮放在片段中。 Then set up the button in your UI by adding it to a fragment and update your activity to use your fragment.