请告诉我如何正确地从 Firebase 读取数据。我根据文档工作,我做了所有这样的事情,但它显示“数据库权限被拒绝”。
package com.example.strike.myapplication;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import stanford.androidlib.SimpleActivity;
public class LoginActivity extends SimpleActivity {
private FirebaseDatabase database;
private DatabaseReference myRef;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
database = FirebaseDatabase.getInstance();
myRef = database.getReference("/animal/PLaNGFwshzOhzys2VhOP");
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String value = dataSnapshot.getValue(String.class);
Toast.makeText(getApplicationContext(), value, Toast.LENGTH_SHORT).show();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), "Value is: " + databaseError, Toast.LENGTH_SHORT).show();
}
});
}
}
规则
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write;
}
}
}
在代码中,您使用的是实时数据库,但您显示了另一个数据库 - Cloud Firestore 的规则。为了让它工作,你需要在 FireBase 控制台中创建一个 RealTime Database,看图:
或者改一下代码,也没什么复杂的。