我正在尝试从android写入Firebase。我只希望经过身份验证的用户能够写入数据库。我该怎么做?
这是我尝试写入数据库的注册片段:
public class register_fragment extends Fragment {
public static final String FIREBASE_URL = "my_apps_url";
private FirebaseAuth mAuth;
private Firebase mRootRef;
public String studentIdString, emailString, passwordString;
Snackbar mSnackbar;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.register_layout, container, false);
Button mRegister = (Button) view.findViewById(R.id.green_register_button);
final EditText mStudentId = (EditText) view.findViewById(R.id.student_id);
final EditText mEmail = (EditText) view.findViewById(R.id.register_email);
final EditText mPassword = (EditText) view.findViewById(R.id.register_password);
mAuth = FirebaseAuth.getInstance();
mRootRef = new Firebase(FIREBASE_URL);
mRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
studentIdString = mStudentId.getText().toString();
emailString = mEmail.getText().toString();
passwordString = mPassword.getText().toString();
registerUser(studentIdString,emailString,passwordString);
}
});
return view;
}
@Override
public void onStart(){
super.onStart();
//Check if user is logged in
FirebaseUser currentUser = mAuth.getCurrentUser();
}
private void registerUser(String id, String email, String password){
mAuth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
mSnackbar = Snackbar.make(getView(),"Error: "+task.getException(),Snackbar.LENGTH_SHORT);
mSnackbar.show();
}else{
mSnackbar = Snackbar.make(getView(),"Successfully Registered",Snackbar.LENGTH_SHORT);
mSnackbar.show();
registerUser(studentIdString,emailString);//call method to write to Firebase
Intent intent = new Intent(getActivity(), ChapelInProgressActivity.class);
intent.putExtra("user",user.getEmail());
startActivity(intent);
}
}
});
}
private void registerUser(String id, String email){
Map<String, Object> updates = new HashMap<>();
updates.put("id",id);
updates.put("email",email);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
mRootRef.child(user.getUid()).updateChildren(updates);//trying to write to Firebase, but does not work
}
}
我希望Firebase数据库的规则为:
".read": "auth != null",
".write": "auth != null"
因此只有经过身份验证的用户才能读写
答案 0 :(得分:2)
如果要使用这些规则,则必须编辑firebase控制台中的规则部分。
但是,如果要检查应用程序中的身份验证状态,可以使用AuthStateListener,更多信息请点击此处: