I want to get data from firebase without changing my database structure because I have two condition:
When admin logins then he can see all employees data for the selected year or say year-wise.
But when employees login then they should be able to see their individual data from all the years using employee code, which is a child also (blue tick in the picture).
Below is my database structure:
The child marked in red is unknown in case of employee's access and the blue tick denotes an employee who may be present in every year.
All I want is to achieve the 2nd condition. But I am unable to get the data. Here is my code:
private void retrieveData() {
final String shift = kvName.getText().toString();
final String employeeCode = empCode.getText().toString();
dbRef.child("Apar").child(shift);
dbRef.orderByChild(employeeCode).equalTo(employeeCode).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot datas1 : dataSnapshot.getChildren()) {
for (DataSnapshot datas2 : datas1.getChildren()) {
// String aparGrading= datas2.getKey(); //unable to figure out how to get
// Toast.makeText(Apar.this, aparGrading, Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
CodePudding user response:
Your current data structure makes it easy to find the information for all employees for a specific year. It does however not make it easy to find the information for a specific employee across all years.
To do the latter, you have two options:
- Check each year for the presence of a node for that employee ID.
- Add an additional data structure that maps from each employee ID to the years for which they have data, and then load each year's data for that employee individually
For more on this, also see:
-
Here is my modified and working code :
private void retrieveData() { final String shift = kvName.getText().toString(); final String employeeCode = empCode.getText().toString(); final DatabaseReference aparRef = dbRef.child("Apar").child(shift); aparRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { list = new ArrayList<>(); if (dataSnapshot.exists()) { for (DataSnapshot dataS1 : dataSnapshot.getChildren()) { if (dataS1.hasChild(employeeCode)) { AparData aparData = dataS1.child(employeeCode).getValue(AparData.class); list.add(aparData); rvAPAR.setHasFixedSize(true); rvAPAR.setLayoutManager(new LinearLayoutManager(Apar.this)); rvAPAR.setItemAnimator(new DefaultItemAnimator()); aparAdapter = new AparAdapter(Apar.this, list); rvAPAR.setAdapter(aparAdapter); } else { Toast.makeText(Apar.this, "No Data Found!!", Toast.LENGTH_SHORT).show(); } } } else { Toast.makeText(Apar.this, "Not Data Found!!", Toast.LENGTH_SHORT).show(); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); }