我使用键将数据保存为数值,其中键是用户尝试的问题。如果用户尝试了所有问题,则可能是连续的。键可能是0,1,2,3 ......这是由Firebase保存为数组(如图像中所示)
JSON是
"parthgupta48@gmail,com": {
"attemptedQuestions": [
{
"answer": "533",
"status": "wrong",
"submissionTime": 1487796702453
},
{
"answer": "9",
"score": 10,
"status": "correct",
"submissionTime": 1487878744867
},
{
"answer": "4",
"status": "wrong",
"submissionTime": 1487956858227
},
{
"answer": "3",
"status": "wrong",
"submissionTime": 1488056247303
},
null,
{
"answer": "25",
"score": 16,
"status": "correct",
"submissionTime": 1488212417465
},
{
"answer": "3",
"status": "wrong",
"submissionTime": 1488380348815
},
null,
null,
null,
{
"answer": "50",
"score": 11,
"status": "correct",
"submissionTime": 1488648738615
}
],
当键不连续时,例如0,9,15 ......当用户只尝试某些问题时会发生这种情况,然后Firebase将其保存为地图(如图像中所示)
JSON是
"priyanshu96,goyal@gmail,com" : {
"attemptedQuestions" : {
"0" : {
"answer" : "667",
"status" : "wrong",
"submissionTime" : 1487773682189
},
"10" : {
"answer" : "50",
"submissionTime" : 1488646361162
}
},
这是我用来在Android中检索数据的代码。
try {
mCurrentUser = child.getValue(UserObject.class);
} catch (Exception e) {
Utils.makeToast("Some Error Occurred ",LoginActivity.this);
}
userObject类
public class UserObject implements Serializable {
private String name;
private String uid;
private String email;
private String photoUrl;
private String contact;//bekaar
private long credits;
public Map<String,AttemptedByUserObject> attemptedQuestions;
public void setAttemptedQuestions(Map<String, AttemptedByUserObject> attemptedQuestions) {
this.attemptedQuestions = attemptedQuestions;
}
public Map<String, AttemptedByUserObject> getAttemptedQuestions() {
return attemptedQuestions;
}
public long getCredits() {
return credits;
}
public void setCredits(long credits) {
this.credits = credits;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhotoUrl() {
return photoUrl;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}}
但是,当数据保存为列表时,问题attemptedQuestions
需要列出,当数据保存为Map
时,问题需要Map
。
我该如何解决这个问题?
答案 0 :(得分:0)
当使用从零(即0、1、2等)开始的连续键保存信息时,您将返回一个列表,在我的情况下,我是从一个开始的,因此由于某种原因它使我回到了列表以null元素开头。当键不连续时,将返回一个Map。了解了这一点之后,我最终通过类型检查对其进行了修补,由于列表中的空值,我删除了第一个元素。
when (it) {
is Map<*, *> -> doSomething(it.values.toList() as List<HashMap<String, Any>>)
is List<*> -> doSomething((it.subList(1,it.size)) as List<HashMap<String, Any>>)
is Any -> return
}
在示例中,doSomething仅接受List<Hashmap<String, Any>>
个参数,但变量it
可以是Map或List。