【发布时间】:2017-01-23 19:44:58
【问题描述】:
我正在尝试迭代具有以下数据快照的嵌套 Firebase 数据库:
DataSnapshot { key = Presidents, value = {1={aspirantName=Uh Ky, thumbnail=434, currentVotes=324595}, position=1, 2={aspirantName=Rao O, thumbnail=3, currentVotes=32}, numberofAspirants=3, docketName=Presidents} }
但是得到这个异常:
com.google.firebase.database.DatabaseException:无法将 java.lang.String 类型的对象转换为 com.example.esir.jualeader.Aspirant 类型
数据快照是来自
的日志private void getAspirantsData(DataSnapshot dataSnapshot) {
aspirantsArrayList.clear(){
Log.e("Ds", "" + dataSnapshot); //Prints DataSnapshot { key = Presidents, value = {1={aspirantName=Uh Ky, thumbnail=434, currentVotes=324595}, position=1, 2={aspirantName=Rao O, thumbnail=3, currentVotes=32}, numberofAspirants=3, docketName=Presidents} }
Iterable<DataSnapshot>iterable=dataSnapshot.getChildren();
Iterator<DataSnapshot>iterator=iterable.iterator();
while (iterator.hasNext()){
Aspirant aspirant=iterator.next().getValue(Aspirant.class); // com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.esir.jualeader.Aspirant
Log.e("Aspirant ", "" + aspirant.getAspirantName()+" "+aspirant.getCurrentVotes()+" "+aspirant.getThumbnail());//This Works therefore Aspirant Object has Been Created
aspirantsArrayList.add(aspirant);
}
}
任何人都可以就异常发生的原因提供帮助吗?它也尝试将哪个字符串转换为我的 Aspirant 对象。
这是我的应聘者课程
public class Aspirant {
private String aspirantName;
private int currentVotes;
private int thumbnail;
public Aspirant(){
}
public Aspirant(String aspirantName, int currentVotes, int thumbnail){
this.aspirantName=aspirantName;
this.currentVotes=currentVotes;
this.thumbnail=thumbnail;
}
public String getAspirantName() {
return aspirantName;
}
public void setAspirantName(String aspirantName) {
this.aspirantName = aspirantName;
}
public int getCurrentVotes() {
return currentVotes;
}
public void setCurrentVotes(int currentVotes) {
this.currentVotes = currentVotes;
}
public int getThumbnail() {
return thumbnail;
}
public void setThumbnail(int thumbnail) {
this.thumbnail = thumbnail;
}
}
以下是我的 Firebase 数据库结构
{
"Presidents" : {
"1" : {
"aspirantName" : "Urhu atta",
"currentVotes" : 324595,
"thumbnail" : 434
},
"2" : {
"aspirantName" : "Rla Oga",
"currentVotes" : 32,
"thumbnail" : 3
},
"docketName" : "Presidents",
"numberofAspirants" : 3,
"position" : 1
},
"Senetors" : {
"docketName" : "Senetors",
"numberofAspirants" : 5,
"position" : 2
}
}
【问题讨论】:
-
您可能想分享您的
Aspirant课程,这可能是问题的原因。 -
` public class Aspirant { private String aspirantName;私人 int currentVotes;私有字符串缩略图; public Aspirant(){ } public Aspirant(String aspirantName, int currentVotes, String thumbnail){ this.aspirantName=aspirantName; this.currentVotes=currentVotes; this.thumbnail=缩略图; }}` 由 Android Studio 生成的所有其他 getter 和 setter
-
@EsirKings 您应该编辑您的问题并将课程代码添加到您的问题中。一行代码很难看懂。
标签: android firebase firebase-realtime-database