以下代码当前读取资源填充并将读取的每个项目呈现给RecyclerView。
public class kos_putra extends Fragment {
ArrayList<Kost> mList = new ArrayList<>();
KostAdapter mAdapter;
DatabaseReference mFirebaseDatabase;
FirebaseDatabase mFirebaseInstance;
public kos_putra() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.kos_putra, container, false);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
mAdapter = new KostAdapter(mList);
recyclerView.setAdapter(mAdapter);
fillData();
return view;
}
private void fillData() {
Resources resources = getResources();
String[] arJudul = resources.getStringArray(R.array.places);
String[] arDeskripsi = resources.getStringArray(R.array.place_desc);
String[] arLokasi = resources.getStringArray(R.array.place_locations);
TypedArray a = resources.obtainTypedArray(R.array.places_picture);
Drawable[] arFoto = new Drawable[a.length()];
for (int i = 0; i < arFoto.length; i++) {
BitmapDrawable bd = (BitmapDrawable) a.getDrawable(i);
RoundedBitmapDrawable rbd =
RoundedBitmapDrawableFactory.create(getResources(), bd.getBitmap());
rbd.setCircular(true);
arFoto[i] = rbd;
}
a.recycle();
for (int i = 0; i < arJudul.length; i++) {
mList.add(new Kost(arJudul[i], arDeskripsi[i], arLokasi[i], arFoto[i]));
}
mAdapter.notifyDataSetChanged();
}
private void fetchDataFromFirebase(){
mFirebaseInstance = FirebaseDatabase.getInstance();
mFirebaseDatabase = mFirebaseInstance.getReference("kos_putra");
}
}
现在,我想从Firebase中读取,而不是从文件中读取。如何在 kos_putra 下迭代每个节点?在下图中,有4个对象。从逻辑上讲,我正在考虑首先获取数据,然后进行for循环。但是仍然不清楚如何做到这一点。
答案 0 :(得分:3)
要迭代每个节点,请执行以下操作:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("kos_putra");
ref.addValueEventListener(new ValueEventListener(){
@Override
public void onDataChange(DataSnapshot dataSnapshot){
for(DataSnapshot data: dataSnapshot.getChildren()){
String deskripsi=data.child("deskripsi").getValue().toString();
String nama=data.child("nama").getValue().toString();
}
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
此处您的数据快照在kos_putra
上,在该位置添加一个侦听器将在所有节点(1,2,3,4)上迭代,并且使用for循环它将获得所有节点内的值