Xamarin.Forms:DependencyService获取Firebase Android数据

时间:2017-05-31 09:58:08

标签: android firebase firebase-realtime-database xamarin.forms

我正在使用Xamarin.Forms为iOS和Android实现相同的UI,但我必须实现分别向Firebase读取和写入数据的功能(它们是不同的)。

我想将Firebase中的所有数据都放到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 个答案:

答案 0 :(得分: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;
}