java - android studio firebase 数据库:如何从子子节点获取数据
问题描述
我正在尝试从我的 firebase 数据库中检索颠簸数据,然后显示颠簸及其从数据库中检索到的信息。
问题是我的数据库包含子子,并且这个子子名称是基于位置的,所以我无法通过子子名称检索数据。
那么有没有一种方法可以检索所有子子名称?所以我可以通过 r 从子子项中检索数据来检索所有数据?
这是我的数据库
这是我检索数据的代码
private void showbumps() {
ref =FirebaseDatabase.getInstance().getReference().child("SpeedBump");
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
List<SpeedBump> bumps = new ArrayList<>();
bumps.clear();
// get bumps info from DB
for (DataSnapshot postSnapshot: snapshot.getChildren()) {
SpeedBump bump = postSnapshot.getValue(SpeedBump.class);
bumps.add(bump);
double bump_lat = bump.getLatitude();
double bump_long = bump.getLongitude();
String bump_type = bump.getType();
String bump_size = bump.getSize();
LatLng latLng = new LatLng(bump_lat,bump_long);
String bump_info = " type : "+ bump_type + " size : "+bump_size ;
// set height & width - apply style
int height = 130;
int width = 130;
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.pin);
Bitmap smallMarker = Bitmap.createScaledBitmap(b, width, height, false);
BitmapDescriptor smallMarkerIcon = BitmapDescriptorFactory.fromBitmap(smallMarker);
// BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.pin);
MarkerOptions marker = new MarkerOptions().position(latLng).title("Bump info").snippet(bump_info).icon(smallMarkerIcon);
// create marker for bumps
mMap.addMarker(marker);
} }
代码没有显示任何凹凸。
解决方案
您快到了。您只需要一个额外的循环来满足 JSON 中未知键的额外级别:
private void showbumps() {
ref =FirebaseDatabase.getInstance().getReference().child("SpeedBump");
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
List<SpeedBump> bumps = new ArrayList<>();
bumps.clear();
for (DataSnapshot locationSnapshot: snapshot.getChildren()) {
for (DataSnapshot bumpSnapshot: locationSnapshot.getChildren()) {
SpeedBump bump = bumpSnapshot.getValue(SpeedBump.class);
...
我发现为快照变量提供清晰的名称以指示它们捕获的数据的哪一部分是最有帮助的。
推荐阅读
- c++ - 外部变量的初始化
- asp.net - .net (C#) MVC 与 OCR 并仅提取特定单词以将其存储到数据库中
- java - 使用 java 编码的天蓝色函数应用程序
- emacs - Emacs 拆分窗口中的 iPython 不能停留在原来的位置
- java - 你能停止 Spring Cloud 重新绑定/重新加载使用 @ConfigurationProperties 注释的 POJO 吗?
- php - Mysql的选择中返回多少行?
- ansible - Ansible/jinja2 YAML 文件中的“:&”是什么意思?
- android - 当应用程序处于后台时,如何为 Firebase 通知显示自定义 UI?
- c++ - Hinnant 的堆栈分配器和异常
- python - 两个服务之间的 Kubernetes 连接?