我是firebase中查询实现的新手。在我的代码中,我使用快照将数据提取到列表视图中。我正在通过List但是进一步阅读,我发现List不能被转换为Datasnaphot,答案需要使用GenericTypeIndicator
。我尝试使用它来将我的数据导入我的listView,但这不会成功。
为什么我会收到此错误Error: The non-generic type 'GenericTypeIndicator' cannot be used type arguments.
?
活动
GenericTypeIndicator<List<GetUserContent>>messages = new GenericTypeIndicator<List<GetUserContent>>(){};
public void OnDataChange(DataSnapshot snapshot)
{
messages.Clear();
var items = snapshot.Child(post_key);
messages.Add((GetUserContent)items);
ViewAdapter adapter = new ViewAdapter(this, messages);
Console.WriteLine("Data being fetched " + items);
mylistview.Adapter = adapter;
}
适配器
internal class ViewAdapter: BaseAdapter
{
private List<GetUserContent> messages;
public ViewAdapter(Activity activity,List<GetUserContent> messages)
{
this.activity = activity;
this.messages = messages;
}
GetUserContent Class
internal class GetUserContent
{
public string Email { get; set; }
public string Message { get; set; }
public GetUserContent()
{
}
public GetUserContent(string Email, string Message){
this.Email = Email;
this.Message = Message;
}
}
发表
mLike.Child(post_key).Child(mAuth.CurrentUser.Uid).Push().SetValue(edtChat.Text);
答案 0 :(得分:0)
为什么我会收到此错误错误:非泛型类型'GenericTypeIndicator'不能使用类型参数。?
我不知道这个库是如何设计的,以及为什么GenericTypeIndicator
不能与类型参数一起使用。您可以在GooglePlayServicesComponents Github Repo上提出问题。
但是提到Work with Lists of Data。您检索的对象是Java.Lang.IIterable<DataSnapShot>
对象,无法直接将其转换为List。您可以使用以下代码转换为List:
public void OnDataChange(DataSnapshot snapshot)
{
var children = snapshot.Child("users")?.Children?.ToEnumerable<DataSnapshot>();
List<HashMap> list = new List<HashMap>();
foreach (DataSnapshot s in children)
{
list.Add((HashMap)s.Value);
}
}
我的Firebase数据库结构如下所示:
<强>更新强>
目前,我无法直接发布我的自定义对象,我不断发现 序列化错误:
`Firebase.Database.DatabaseException: No properties to serialize found on class md5f5cedb36bdcec41a9de7aed50a9aade0.User`.
但是我使用HashMap
作为中间类型来解决它:
public class User:Java.Lang.Object
{
public User() {}
// convert current User to HashMap
public HashMap ToMap()
{
HashMap map = new HashMap();
map.Put("username", this.username);
map.Put("email", this.email);
return map;
}
public string username;
public string email;
public User(string username, string email)
{
this.username = username;
this.email = email;
}
}
并发布这样的数据:
FirebaseDatabase.Instance
.Reference
.Child("users")
.Push()
.SetValue(new User("username", "email").ToMap());
尚未完成检索HashMap
并将其转换回User
列表:
public void OnDataChange(DataSnapshot snapshot)
{
var children = snapshot.Child("users")?.Children?.ToEnumerable<DataSnapshot>();
List<User> list = new List<User>();
HashMap map;
foreach (DataSnapshot s in children)
{
map = (HashMap)s.Value;
list.Add(new User(map.Get("username")?.ToString(), map.Get("email")?.ToString()));
}
}