【问题标题】:java.lang.NullPointerException Xamarin Facebook Android SDKjava.lang.NullPointerException Xamarin Facebook Android SDK
【发布时间】:2016-07-28 13:21:22
【问题描述】:

我正在尝试在我的游戏中实现 Facebook Android SDK,但是当我尝试使用 facebook 登录时,它会崩溃并生成此错误

  Java.Lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
  at --- End of managed exception stack trace ---
  at java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
  at at com.facebook.login.LoginClient.getLogger(LoginClient.java:369)
  at at com.facebook.login.LoginClient.logAuthorizationMethodComplete(LoginClient.java:419)
  at at com.facebook.login.LoginClient.tryNextHandler(LoginClient.java:202)
  at at com.facebook.login.GetTokenLoginMethodHandler.getTokenCompleted(GetTokenLoginMethodHandler.java:119)
  at at com.facebook.login.GetTokenLoginMethodHandler$1.completed(GetTokenLoginMethodHandler.java:74)
  at at com.facebook.internal.PlatformServiceClient.callback(PlatformServiceClient.java:157)
  at at com.facebook.internal.PlatformServiceClient.handleMessage(PlatformServiceClient.java:141)
  at at com.facebook.internal.PlatformServiceClient$1.handleMessage(PlatformServiceClient.java:62)
  at at android.os.Handler.dispatchMessage(Handler.java:102)
  at at android.os.Looper.loop(Looper.java:234)
  at at android.app.ActivityThread.main(ActivityThread.java:5526)
  at at java.lang.reflect.Method.invoke(Native Method)
  at at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
  at at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

这是我的主要活动类

public class MainActivity : AndroidGameActivity
    {
        int count = 1;
        protected override void OnActivityResult (int _requestCode, Result _resultCode, Intent _intent)
        {

            GooglePlayServicesManager.instance.OnActivityResult(_requestCode, _resultCode, _intent); 
        }


        protected override void OnCreate (Bundle savedInstanceState)
        {
            base.OnCreate (savedInstanceState);

            var g = new Game1();

            Social.SocialManager.OnCreate_Android(this);
            FacebookManager.mInstance.InitFacebookSDK (this.ApplicationContext, this);
            SetContentView(g.Services.GetService<View>());


            g.Run();
        }

        protected override void OnDestroy()
        {
            base.OnDestroy();
        }

        protected override void OnStart()
        {
            base.OnStart();
            Console.WriteLine("activity::onstart");
        }

        protected override void OnStop()
        {
            base.OnStop();
            Console.WriteLine("activity::onstop");
        }

        protected override void OnResume()
        {
            base.OnResume();
            //SpringAdvert.AdvertManager.OnAppResume();
        }

        protected override void OnPause()
        {
            base.OnPause();
            //SpringAdvert.AdvertManager.OnAppPause();
        }

        public override void OnConfigurationChanged(Android.Content.Res.Configuration newConfig)
        {
            base.OnConfigurationChanged(newConfig);
        }
    }

这是 InitFacebookSDK

public void InitFacebookSDK(Android.Content.Context Context, Android.App.Activity Activity)
        {
            if(!FacebookSdk.IsInitialized)
            {
                //Initialize the whole sdk
                FacebookSdk.SdkInitialize(Context);
                activity = Activity;
            }

            #if DEBUG
                Console.WriteLine ("Facebook SDK Initialized: " + FacebookSdk.IsInitialized);
            #endif

            //Creates a callback manager to handle the callbacks facebook have
            CallbackManager = CallbackManagerFactory.Create ();

            var loginCallback = new FacebookCallback<LoginResult> {
                HandleSuccess = loginResult => {
                    HandlePendingAction ();

                },
                HandleCancel = () => {
                    if (pendingAction != PendingAction.NONE) {

                        pendingAction = PendingAction.NONE;
                    }

                },
                HandleError = loginError => {
                    if (pendingAction != PendingAction.NONE
                        && loginError is FacebookAuthorizationException) {

                        pendingAction = PendingAction.NONE;
                    }

                }
            };
            LoginManager.Instance.RegisterCallback (CallbackManager, loginCallback);


        }

我试图让我有一个自定义按钮供玩家按下,而不是使用 facebook 提供的标准按钮登录,所以我调用以下函数来触发登录

public void LoginToFacebook ()
        {
            LoginManager.Instance.LogInWithReadPermissions (activity, new List<string> { "user_friends" });
            #if DEBUG
            Console.WriteLine ("Logging into facebook");
            #endif
        }

当我按下自定义按钮登录时,会导致开始时显示 Java.lang.NullPointerException 错误。

我已经完成了所有必要的步骤,比如生成 keyhash、在 facebook 上注册应用、将所有必要的东西添加到 AndroidManifest 中。

编辑:我忘了提到上面显示的主要活动与 InitFacebookSDK 位于不同的项目中,我只是引用它所在的项目并在 MainActivity 中调用它。我正在尝试将 Facebook 实施到一个项目中,当我下次尝试将 Facebook 实施到另一个项目中时,我可以轻松地参考该项目。

编辑:当我第一次初始化 Facebook SDK 时,我传入了一个 android.activity,然后将其存储在 Facebook 管理器中,然后我将使用它通过将其传递给 LoginWithReadPermission 来登录。

编辑:我尝试将任何与 Facebook 相关的内容放在主活动中,它仍然返回空指针异常错误。就像注册回调一样,从 IFacebookCallback 中获取 MainActivity 引用,然后在注册回调后登录。

编辑:这是我的 Android 清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.test.testing">
    <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="23" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:allowBackup="true" android:icon="@mipmap/icon" android:label="@string/app_name">       
        <!-- To access Facebook APIS-->
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.INTERNET" />
        <meta-deta android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
        <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>
</manifest>

这是我的 string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, Click Me!</string>
    <string name="app_name">testing</string>
    <string name="facebook_app_id">xxxxxxxxxxxx</string>
</resources>

【问题讨论】:

    标签: xamarin xamarin.android facebook-android-sdk


    【解决方案1】:

    原来 Facebook SDK 没有读取我在 String.XML 中声明的 Facebook App ID,您必须在使用 FacebookSdk.ApplicationId = "Your ID HERE"; 初始化 SDK 后手动设置它;

    【讨论】:

      【解决方案2】:

      据我所知,您用于实现 facebook 回调的方法无法正常工作。

      更好的是在你想拥有你的回调函数的类中使用 IFacebookCallback。之后创建一个配置文件跟踪器,帮助您了解用户登录是否更改。

          #region MyProfileTracker classe
          public class MyProfileTracker : ProfileTracker
          {
              public event EventHandler<OnProfileChangedEventArgs> mOnProfileChanged;
      
              protected override void OnCurrentProfileChanged(Profile oldProfile, Profile newProfile)
              {
                  if (mOnProfileChanged != null)
                  {
                      mOnProfileChanged.Invoke(this, new OnProfileChangedEventArgs(newProfile));
                  }
              }
          }
          #endregion
      
          #region OnProfileChangedEventArgs classe
          public class OnProfileChangedEventArgs : EventArgs
          {
              public Profile mProfile;
              public OnProfileChangedEventArgs(Profile profile)
              {
                  mProfile = profile;
              }
          }
      #endregion
      

      目前我没有简单的代码示例,但您可以查看我为 android xamarin developmentpment 推荐的这个 youtube 频道:

      https://www.youtube.com/watch?v=OYTe0ZWKAOU&list=PLCuRg51-gw5VqYchUekCqxUS9hEZkDf6l&index=65

      最后一件事,我在我的应用程序中重新连接时遇到了一些问题,最好为此创建你的方法,这里是我的重新连接代码:

              /// <summary>
              /// Test if current facebook token exist and reconnect to application if needed
              /// </summary>
              /// <param name="currentAccessToken">current facebook session</param>
              private async void updateWithToken(AccessToken currentAccessToken)
              {
      
                  if (currentAccessToken != null)
                  {
                      User.Instance.Facebook_Id = currentAccessToken.UserId;
                      //Save token for next connection
                      LocalSaving ls = new LocalSaving();
                      var sToken = ls.RetrieveToken();
                      //save token into singleton
                      Core.WService.Token.Instance.SaveTokenInfo(sToken);
      
                      FindViewById<LoginButton>(Resource.Id.login_button).Visibility = ViewStates.Gone;
                      progressBar.Visibility = ViewStates.Visible;
                      loadingTextView.Visibility = ViewStates.Visible;
                      await onLoadInformation();
                      progressBar.Visibility = ViewStates.Invisible;
                      loadingTextView.Visibility = ViewStates.Invisible;
                  }
      
      }
      

      希望对你有帮助。

      【讨论】:

      • 感谢您的建议,但它不起作用:/ 我忘了提到上面显示的主要活动与 InitFacebookSDK 不同的项目,我只是引用它所在的项目并调用它主活动。
      • 好的,我从来没有使用过你的工具,所以我想我帮不了你
      • 我目前正在关注您从 xamarin 下载组件时获得的 HelloFacebookSample
      猜你喜欢
      • 1970-01-01
      • 2015-12-22
      • 1970-01-01
      • 1970-01-01
      • 2017-01-24
      • 2018-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多