从 firebase 获取值
- 创建类并添加导入以解析信息:
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.IgnoreExtraProperties;
//Declaration of firebase references
private DatabaseReference mDatabase;
//Declaration of firebase atributtes
public String uID;
public String username;
public String email;
@IgnoreExtraProperties
public class User {
//Default constructor
public User() {
//Default constructor required for calls to DataSnapshot.getValue(User.class)
mDatabase = FirebaseDatabase.getInstance().getReference();
//...
}
//...
}
- 将
addListenerForSingleValueEvent()
添加到我们的数据库参考:
//Add new imports
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.ValueEventListener;
//...
public void getUser(String uID){
//The uID it's unique id generated by firebase database
mDatabase.child("users").child(uID).addListenerForSingleValueEvent(
new ValueEventListener () {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// ...
}
@Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
}
});
}
- 在
onDataChange()
活动中通过 firebase 信息为我们的类充气:
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Inflate class with dataSnapShot
Users user = dataSnapshot.getValue(Users.class);
//...
}
- 最后,通常我们可以从 firebase 类获得不同的属性:
//User inflated
Users user = dataSnapshot.getValue(Users.class);
//Get information
this.uID = user.uID;
this.username = user.username;
this.email = user.email;
最佳做法
- firebase 支持 32 个不同的子级别,然后很容易编写错误的引用,以转义这个创建最终的私有引用:
//Declaration of firebase references
//...
final private DatabaseReference userRef = mDatabase.child("users").child("premium").child("normal").getRef();
//...
public void getUser(String uID){
//Call our reference
userRef.child(uID).addListenerForSingleValueEvent(
new ValueEventListener () {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// ...
}
@Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
}
});
}
- 当用户无法通过数据库规则访问此引用时,将调用
onCancelled()
事件。如果需要,添加相关代码来控制此异常。
有关更多信息,请访问官方文档