2016-05-16 15 views
1

私は自分のアプリでFacebookのログインを実装しようとしていますが、いつでも私のアプリを起動するとクラッシュします。私はfacebook developerサイトに従っています。ここに私のコードです。私のアンドロイドアプリでFacebookのログインが機能していません

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) 

HELしてくださいこの問題を解決するために私に教えてください。前もって感謝します!代わりに

loginButton.findViewById(R.id.login_button); 

使用

findViewById(R.id.login_button); 

+0

'Logcat'の一部を投稿してください。 –

+0

あなたはgetting @ Algor7である実際のエラーは何ですか?それはnullポインタ例外です。 – Lampard

+0

はい、それらのほとんどはnullポインタ例外です.. – Algor7

答えて

0

問題はloginButtonnullであることを意味は何

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内のビューlogin_buttonがまだ初期化されていないことを確認しようとしています。代わりにアクティビティ内のビューを見つける必要があります。

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(); 
      } 
     }); 
    } 
+0

あなたは完全なコードを提供しました。それは問題ではありません。彼はむしろこのコードから何も学ばず、彼のコードの中で何が問題であるか知っています。彼に解決策を提供するだけでは不都合ではありません;彼は自分が間違っていることを知ることも重要です。 –

+0

しかし、私はLoginManagerの代わりにLoginButtonを使いたいです。 – Algor7

関連する問題