我正在尝试从Firebase数据库获取此嵌套数据。我已将Company,Vehicle和Destination划分为三个类。我想检索任何建议的数据。我只检索公司信息,而不检索其两个子级的车辆和目的地。
公共类MainActivity扩展了AppCompatActivity {
private DatabaseReference myRef;
private TextView tvID, tvCompanyName, tvCompanyAddress, tvCompanyContact, tvCompanyStatus, tvCarNumber;
private String startingPoint, endingPoint, fare, car, carModel, carNumber;
private Button btnGo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvID = findViewById(R.id.tvID);
tvCompanyName = findViewById(R.id.tvCompanyName);
tvCompanyAddress = findViewById(R.id.tvCompanyAddress);
tvCompanyContact = findViewById(R.id.tvCompanyContact);
tvCompanyStatus = findViewById(R.id.tvCompanyStatus);
tvCarNumber = findViewById(R.id.tvCarNumber);
myRef = FirebaseDatabase.getInstance()。getReferenceFromUrl(“ https://travel-cdae5.firebaseio.com/company/companies”);
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
try {
Company company = dataSnapshot.getValue(Company.class);
Destination destination = dataSnapshot.getValue(Destination.class);
tvID.setText(company.getId());
tvCompanyName.setText(company.getName());
tvCompanyAddress.setText(company.getAddress());
tvCompanyContact.setText(company.getContact());
tvCompanyStatus.setText(destination.getFare());
} catch (Exception exp) {
Log.e("Message", exp.getMessage());
Toast.makeText(MainActivity.this, exp.getMessage()
, Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onCancelled(DatabaseError error) {
Toast.makeText(MainActivity.this, error.getMessage()
, Toast.LENGTH_SHORT).show();
}
});
}
}
答案 0 :(得分:1)
目的地是公司节点的子节点,这就是为什么您必须使用DataSnapshot destinationsSnapshot = dataSnapshot.child("destinations").getValue();
然后,您需要遍历返回的目的地。
代码:
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
try {
Company company = dataSnapshot.getValue(Company.class);
tvID.setText(company.getId());
tvCompanyName.setText(company.getName());
tvCompanyAddress.setText(company.getAddress());
tvCompanyContact.setText(company.getContact());
DataSnapshot destinationsSnapshot = dataSnapshot.child("destinations").getValue();
// Now iterate over the destinations
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
if (snapshot.exists()) {
if (snapshot.getKey().equals(0)){
Destination destination = snapshot.getValue(Destination.class);
tvCompanyStatus.setText(destination.getFare());
}
}
}
} catch (Exception exp) {
Log.e("Message", exp.getMessage());
Toast.makeText(MainActivity.this, exp.getMessage()
, Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onCancelled(DatabaseError error) {
Toast.makeText(MainActivity.this, error.getMessage()
, Toast.LENGTH_SHORT).show();
}
});