2017-05-31 87 views
1

我正在使用Xamarin.Forms爲iOS和Android實現相同的UI,但我必須實現將數據分別讀寫到Firebase的功能(它們是不同的)。Xamarin.Forms:DependencyService獲取Firebase Android數據

我想把從火力地堡中的所有數據,以一個ObservableCollection,這樣的:

ObservableCollection<Post> posts; 
posts = DependencyService.Get<IFeed>().getPosts(); 

這被稱爲Android的代碼是:

ObservableCollection<Post> posts = new ObservableCollection<Post>(); 

    public FeedAndroid() 
    { 
     database = FirebaseDatabase.GetInstance(MainActivity.app); 
     dataRef = database.Reference; 
     postsRef = dataRef.Child("posts"); 

     posts.Clear(); 

     postsRef.AddChildEventListener(this); 
    } 

    public void OnChildAdded(DataSnapshot snapshot, string previousChildName) 
    { 
     Post newPost = new Post { Title = snapshot.Child("title")?.GetValue(true)?.ToString(), 
     Desc = snapshot.Child("desc")?.GetValue(true)?.ToString(), 
     Img = snapshot.Child("image")?.GetValue(true)?.ToString()}; 

     posts.Add(newPost); 
    } 

    public ObservableCollection<Post> getPosts() 
    { 
     return posts; 
    } 

但是,這是行不通的。想知道該怎麼做?

回答

1

我想你的FeedAndroid()是你的類的構造函數實現你的IFeed接口。您的FirebaseDatabase實例是在此構造函數中創建的,這可能是此處的問題。我建議在MainActivity中執行它。例如:

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity, IChildEventListener 
{ 
    public DatabaseReference postsRef; 
    public static ObservableCollection<Post> collection = new ObservableCollection<Post>(); 

    protected override void OnCreate(Bundle bundle) 
    { 
     TabLayoutResource = Resource.Layout.Tabbar; 
     ToolbarResource = Resource.Layout.Toolbar; 

     base.OnCreate(bundle); 

     global::Xamarin.Forms.Forms.Init(this, bundle); 
     LoadApplication(new App()); 
    } 

    protected override void OnResume() 
    { 
     base.OnResume(); 

     FirebaseApp.InitializeApp(this); 

     FirebaseAuth mAuth = FirebaseAuth.Instance; 
     FirebaseUser user = mAuth.CurrentUser; 
     if (user == null) 
     { 
      var result = mAuth.SignInAnonymously(); 
     } 

     postsRef = FirebaseDatabase.Instance.Reference.Child("posts"); 
     postsRef.AddChildEventListener(this); 
    } 

    public void OnCancelled(DatabaseError error) 
    { 
     //TODO: 
    } 

    public void OnChildAdded(DataSnapshot snapshot, string previousChildName) 
    { 
     collection.Add(new Post() {//Your Data here}); 
    } 

    public void OnChildChanged(DataSnapshot snapshot, string previousChildName) 
    { 
     //TODO: 
    } 

    public void OnChildMoved(DataSnapshot snapshot, string previousChildName) 
    { 
     //TODO: 
    } 

    public void OnChildRemoved(DataSnapshot snapshot) 
    { 
     //TODO: 
    } 
} 

而在你FeedAndroid類簡單地返回此collection

public ObservableCollection<Post> getPosts() 
{ 
    return MainActivity.collection; 
}