我正在使用ListView,它将从firebase读取数据。 我的实时数据库的结构是
databaase-d2b83
-----分类
----------水果
--------------- apple:101
----------蔬菜
----------------葱:102
----------------番茄:103
public class MainActivity extends AppCompatActivity {
ListView listView ;
FirebaseDatabase firebaseDatabase ;
DatabaseReference databaseReference ;
ArrayList<String> arrayList ;
ArrayAdapter<String> arrayAdapter ;
String string , val = "Categories" ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
arrayList = new ArrayList<>() ;
arrayAdapter = new ArrayAdapter<>(this , R.layout.listcategories , R.id.textView , arrayList) ;
listView = findViewById(R.id.list) ;
firebaseDatabase = FirebaseDatabase.getInstance() ;
databaseReference = firebaseDatabase.getReference() ;
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
string = ds.getKey().toString() ;
arrayList.add(string) ;
}
listView.setAdapter(arrayAdapter);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
}) ;
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
val = ((TextView)view).getText().toString() ;
Toast.makeText(MainActivity.this , val, Toast.LENGTH_SHORT).show();
arrayList.clear();
listView.setAdapter(arrayAdapter);
databaseReference = firebaseDatabase.getReference(val) ;
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot1) {
for(DataSnapshot ds : dataSnapshot1.getChildren())
arrayList.add(ds.getKey()) ;
listView.setAdapter(arrayAdapter);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
}
当我运行应用程序时,它显示第二个孩子,即“蔬菜”。当为第二个子项(Fruits或Veggies)中的任何一个调用setOnItemClickListener()时,不会获得下一个子项。此时,“dataSnapshot”的getChildernCount()变为零。