我有这个Firebase数据库:
Student
12312343423 (userid)
date:10/10/1921
name:peter
12321321322 (userid)
date:10/12/1924
name: john
现在使用此代码检索数据:
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
String name=data.child("name").getValue().toString();
name1.setText(name);
}}
问题在于for loop
:
for (DataSnapshot data : dataSnapshot.getChildren())
它正在遍历所有孩子,所以如果我有100名学生,它将通过所有需要时间加载的用户。如何让它仅通过登录用户?(此代码在登录后的活动中)。
答案 0 :(得分:1)
如果您只想为当前用户加载数据,那就简单多了:
with open('csv1.csv', 'r') as f:
first = {rows[0]: rows[1:] for rows in list(csv.reader(f))}
with open('csv2.csv', 'r') as f:
for row in csv.reader(f):
if row[0] in first: # row[0] = url
first[row[0]].append(row[2])
merged = [(k,) + tuple(v) for k, v in first.items()]
with open('output.csv', 'w') as f:
csv.writer(f).writerows(merged)
此处不再需要DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Student");
String uid = FirebaseAuthentication.getInstance().getCurrentUser().getUid();
ref.child(uid).addListenerForSingleValueEvent(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
String name=dataSnapshot.child("name").getValue().toString();
name1.setText(name);
}
内的循环,因为您直接访问当前用户的节点。
答案 1 :(得分:0)
我假设您有一个Custom类,其中包含数据库中使用的所有变量的所有getter setter方法。
DatabaseReference mDatabaseReference;
FirebaseUser firebaseUser;
private FirebaseAuth mAuth;
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Student");
mAuth = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null) {
// User is signed in, do all actions you need to perform.
String name = user.getDisplayName();
String date = user.getDate();
} else {
// User is not signed in, prompt to login again.
}
}
};
您可以在Git Here.上获取整个项目的完整详细信息和指南 有关详细信息,请参阅Firebase Android身份验证指南Here.