Java instanceof不适用于从Firebase实时数据库的父类对象列表中提取子类
我有以下三门课: 母公司 儿童1Java instanceof不适用于从Firebase实时数据库的父类对象列表中提取子类,java,android,firebase,arraylist,firebase-realtime-database,Java,Android,Firebase,Arraylist,Firebase Realtime Database,我有以下三门课: 母公司 儿童1 class Child1 extends Parent{ public String c1title; public Child1(){} public void setC1title(String title){ this.c1title = title; } public String getC1itle(){ return this.c1title; } } 儿童2 class Child2 extends Par
class Child1 extends Parent{
public String c1title;
public Child1(){}
public void setC1title(String title){
this.c1title = title;
}
public String getC1itle(){
return this.c1title;
}
}
儿童2
class Child2 extends Parent{
public String c2title;
public Child2(){}
public void setC2title(String title){
this.c2title = title;
}
public String getC2itle(){
return this.c2title;
}
}
我将子类的实例存储在ArrayList列表中,并将ArrayList上载到RealtimeDatabase。我可以成功地检索ArrayList,但是这段代码无法按照从Firebase检索到的ArrayList的预期工作,但适用于本地ArrayList:
for(Parent p : list){ //list is the ArrayList<Parent> obtained from Firebase
if(p instanceof Child1){
Log.d("Activity1", "1st child");
}
if(p instanceof Child2){
Log.d("Activity1", "2nd child");
}
else{
Log.d("Activity1", "No match found");
}
}
我无法理解背后的原因。本地存储的ArrayList是否有一些关于存储在Firebase中时丢失的存储对象的附加信息?过滤出子对象的理想解决方法应该是什么
编辑:从Firebase检索ArrayList的代码
mDatabaseReference = FirebaseDatabase.getInstance().getReference("test");
mDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
GenericTypeIndicator<ArrayList<Parent>> t = new GenericTypeIndicator<ArrayList<Parent>>() {};
ArrayList<Parent> yourStringArray = dataSnapshot.getValue(t);
List<Parent> list = dataSnapshot.getValue(t);
Log.d(TAG, "Successfully obtained the test list");
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
要从正在使用的数据库中读取数据,请执行以下操作:
GenericTypeIndicator<ArrayList<Parent>> t = new GenericTypeIndicator<ArrayList<Parent>>() {};
ArrayList<Parent> yourStringArray = dataSnapshot.getValue(t);
List<Parent> list = dataSnapshot.getValue(t);
然后在读回时,您将读取数据,循环结果,并根据type属性实例化正确的类:
mDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
String type = child.getChild("type").getValue(String.class);
if ("Child1".equals(type)) {
Child1 child1 = child.getValue(Child1.class);
}...
}
}
我不认为有任何方法可以通过一个API调用在整个子列表上实现这一点。可以发布从Firebased检索日期的代码。看起来您得到的是正常的,因为您使用的是父类。但是,当我使用我在本地创建的同一ArrayList时,过滤工作正常。你能解释一下为什么本地的ArrayList有效吗。
if (object instanceof "Child1") {
ref.child("type").set("Child");
}...
mDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
String type = child.getChild("type").getValue(String.class);
if ("Child1".equals(type)) {
Child1 child1 = child.getValue(Child1.class);
}...
}
}