我正在尝试将所有字段从文档移至ListView
。我已经尝试过foreach循环,但是没有用。
dbRef.collection("Shopkeeper Own Shops").document("Shopkeeper@gmail.com")
.get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
// Get all fields to a list
}
});
答案 0 :(得分:1)
要获取字段,请使用以下内容:
DocumentReference docRef = db.collection("Shopkeeper Own Shops").document("Shopkeeper@gmail.com");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Log.d(TAG, "DocumentSnapshot data: " + document.getData());
Log.d(TAG,"String value: " + document.getString("names"));
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
public Map<String, Object> getData ()
将文档的字段返回为Map,如果文档不存在,则返回null。字段值将转换为其本地Java表示形式。
或者您可以使用getString()
答案 1 :(得分:1)
尝试一下
List<Type> types = documentSnapshots.toObjects(Type.class);
您的示例将是这样
dbRef.collection("Shopkeeper Own Shops").document("Shopkeeper@gmail.com")
.get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if(documentSnapshots.isEmpty()){
Log.d("MyLogger", "Empty Document!");
}else{
// Get all fields to a list
List<MyModel> types = documentSnapshots.toObjects(MyModel.class);
}
}
});
public class MyModel{
// Define fields
private String id;
private String name; // ...etc
// GETTER/SETTER,
}
答案 2 :(得分:1)
要将文档中所有属性的所有值添加到列表中,请使用以下代码行:
dbRef.collection("Shopkeeper Own Shops").document("Shopkeeper@gmail.com").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
List<String> list = new ArrayList<>();
Map<String, Object> map = document.getData();
if (map != null) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
list.add(entry.getValue().toString());
}
}
//So what you need to do with your list
for (String s : list) {
Log.d("TAG", s);
}
}
}
}
});
答案 3 :(得分:1)
尝试一下,
确保您在manifest
中具有 Internet权限,
您的项目已连接到Firebase。
private static final String KEY_NAME = "name";
public void loadName() {
db.collection("users").document()
.get()
.addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
String name = document.getString(KEY_NAME);
} else {
Toast.makeText(activity_home.this, "Error", Toast.LENGTH_LONG).show();
}
}
});
}