2015-05-17 33 views
0

我創建了一個使用Facebook登錄的函數。Xamarin.Auth OAuth2Authenticator Facebook NullReferenceException

public void Login() 
{ 
    var ctx = Forms.Context as MainActivity; 
    var accounts = 
     new List<Account>(AccountStore.Create (ctx).FindAccountsForService (SERVICE)); 
    if (accounts.Count == 1) { 
     GetAccount (accounts [0]); 
     return; 
    } 

    var auth = new OAuth2Authenticator (
     clientId: FBID, 
     scope: string.Empty, 
     authorizeUrl: new Uri (AUTH_URL), 
     redirectUrl: new Uri (REDIRECT_URL)); 

    auth.Completed += (sender, eventArgs) => { 
     AccountStore.Create (ctx).Save (eventArgs.Account, "Facebook"); 
     GetAccount (eventArgs.Account); 
    }; 
    ctx.StartActivity (auth.GetUI (ctx)); 
} 

的事情是,當我在FB登錄頁面輸入我的憑據,到達Completed事件之前拋出一個異常。
我已經從GitHub下載了Xamarin.Auth項目,試圖調試程序,但不幸的是它不會在斷點處中斷。

Caused by: JavaProxyThrowable: System.NullReferenceException: Object reference not set to an instance of an object 
at Xamarin.Auth.OAuth2Authenticator.OnRetrievedAccountProperties (System.Collections.Generic.IDictionary`2) [0x00017] in d:\Downloads\Xamarin.Auth-master\Xamarin.Auth-master\src\Xamarin.Auth\OAuth2Authenticator.cs:373 
at Xamarin.Auth.OAuth2Authenticator.OnRedirectPageLoaded (System.Uri,System.Collections.Generic.IDictionary`2,System.Collections.Generic.IDictionary`2) [0x00016] in d:\Downloads\Xamarin.Auth-master\Xamarin.Auth-master\src\Xamarin.Auth\OAuth2Authenticator.cs:282 
at Xamarin.Auth.WebRedirectAuthenticator.OnPageEncoun...[intentionally cut off]

我一直在努力解決這個問題。請幫忙!

+0

可能重複[?什麼是一個NullReferenceException,我如何修復它(http://stackoverflow.com/questions/4660142/what-is- A-的NullReferenceException和知識-DO-I-FIX-IT) –

回答

0

我找到了!這是混合的情況。
我的調試器沒有停在斷點處(不知道爲什麼)。
造成問題的原因是我在OnCreate()方法中使用上述Login方法創建了一個對象。
然後,我將EventHandler附加到該對象的事件。
Authenticator從他的Intent返回的那一刻,我的對象被綁定的上下文消失了。
這可能有點模糊理解,但也許有些代碼將進一步澄清。

//Not working, causes the problem 
public class MyActivity { 
    MyAuthenticator auth; //the object containing Login(); 
    public void OnCreate() { 
     auth=new MyAuthenticator(); 
     auth.LoggedIn += blabla; 
    } 
    public void SomeMethod() { 
     auth.Login(); 
    } 
} 

溶液:

//Working, own scope 
public class MyActivity { 
    public void OnCreate() { 
     //ILB 
    } 
    public void SomeMethod() { 
     var auth=new MyAuthenticator(); 
     auth.LoggedIn += blabla; 
     auth.Login(); 
    } 
} 
相關問題