我正在使用xamarin.forms实现相同的UI对iOS和Android实现,但是我必须实现单独读取和写入数据的功能(它们是不同的(。
我想将所有数据从firebase放在观察力的情况下,这样:
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;
}
但这不起作用。有什么想法?
我想您的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;
}