![](/img/trans.png)
[英]How to get dataSnapshot.getChildrenCount() inside the children
[英]Get Children in JSON DataSnapshot
我试图分别从JSON中获取子项,并通过意图传递它们。 这是我的JSON格式的方式:
"allDeeJays" : {
"-LeP1DB6Onzh4-UiN_0E" : {
"acct" : "Aaron A",
"djName" : "uhgvvvbbb"
}
},
使用DataSnapshot,我可以使用以下代码获取djName
值,但无法获取acct
值:
@Override
protected void onBindViewHolder(@NonNull ResultsViewHolder holder, final int position, @NonNull final DataSnapshot snapshot) {
// Here you convert the DataSnapshot to whatever data your ViewHolder needs
String s = "";
for(DataSnapshot ds : snapshot.getChildren())
{
s = ds.getValue(String.class);
DjProfile model = new DjProfile(s);
model.setDjName(s);
holder.setDjProfile(model);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("allDeeJays");
String acct = "";
String name = "";
for(DataSnapshot ds : snapshot.getChildren())
{
name = ds.getValue(String.class);
acct = ds.getValue(String.class);
DjProfile model = new DjProfile(name);
model.setDjName(name);
}
Intent i = new Intent(getApplication(), AddSongRequest.class);
i.putExtra("DjName", name);
i.putExtra("UserAcct", acct);
startActivity(i);
}
});
}
};
最后,我的DjProfile类定义如下:package com.example.android.heydj;
导入com.google.firebase.database.Exclude; 导入com.google.firebase.database.PropertyName;
public class DjProfile
{
String djName;
String key;
public DjProfile(String djName)
{
this.djName = djName;
}
public DjProfile(){}
public void setDjName(String djName)
{
this.djName = djName;
}
public String getdjName()
{
return djName;
}
}
这两个变量都返回相同的值,当我运行snapshot.getChildrenCount()
它说有两个子代(我认为是acct和djName)。 我是否需要为帐户名添加其他获取器和设置器? 任何帮助是极大的赞赏 :)
像这样尝试,它将为您的钥匙返回确切的值
if(snapShot.getKey().equalsIgnoreCase("djName"))
name = ds.getValue(String.class);
if(snapShot.getKey().equalsIgnoreCase("acct"))
acct = ds.getValue(String.class);
或使用
DjProfile model = snapShot.getValue(DjProfile.class);
代替
for(DataSnapshot ds : snapshot.getChildren())
{
name = ds.getValue(String.class);
acct = ds.getValue(String.class);
DjProfile model = new DjProfile(name);
model.setDjName(name);
}
您可以通过添加以下行来解决此问题-
DjProfile profile = ds.getValue(DjProfile.class);
您现在可以将此配置文件传递给Intent。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.