简体   繁体   English

Android studio Firebase Firestore 无法检索字段数据

[英]Android studio Firebase Firestore cann't retrieve field data

I'm trying to retrieve the value from the string field group_name in firestore but I get a NullPointerException because the value doesn't get retrieved and added to an arraylist.我正在尝试从 firestore 中的字符串字段 group_name 检索值,但我得到 NullPointerException,因为该值没有被检索并添加到 arraylist。 So the arraylist is empty.所以 arraylist 是空的。 I'm trying to get the data within OnCreateView, because I'm working with fragments.我正在尝试在 OnCreateView 中获取数据,因为我正在处理片段。 Adding data works perfectly (createNewGroup()).添加数据效果很好(createNewGroup())。 错误

火库

    @Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mAuth = FirebaseAuth.getInstance();
    currentUser = mAuth.getCurrentUser();
    db = FirebaseFirestore.getInstance();
    //FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder().setPersistenceEnabled(true).setCacheSizeBytes(FirebaseFirestoreSettings.CACHE_SIZE_UNLIMITED).build();
    //db.setFirestoreSettings(settings);
}



    groupList = new ArrayList<>();
    gridView = view.findViewById(R.id.notes_gridview);
    //Source source = Source.CACHE;
    //https://firebase.google.com/docs/firestore/query-data/get-data#source_options
    db.collection("groups").document(key).get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
        @Override
        public void onSuccess(DocumentSnapshot documentSnapshot) {
            if (documentSnapshot.exists()) {
                groupList.add(documentSnapshot.getString("group_name"));
                Log.w(TAG, "DocumentSnapshot data: " + documentSnapshot.getData());
                adpter = new GroupAdapter(getActivity(), groupList);
                gridView.setAdapter(adpter);
                mProgressCircle.setVisibility(View.INVISIBLE);
            } else {
                Log.w(TAG, "No such document");
            }
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.w(TAG, "Error getting documents: " + e.getMessage());
        }
    });

private void CreateNewGroup(String groupName) {
    HashMap<String, String> groupData = new HashMap<>();
    groupData.put("group_name", groupName);
    HashMap<String, Object> update = new HashMap<>();
    update.put(key, groupData);
    db.collection("groups").document(key).set(update).addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void unused) {
            Log.w(TAG, "New group added successfully to Firestore");
            ((NavigationHost) getActivity()).navigateTo(new MyGroupsFragment(), false);
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Toast.makeText(getActivity(), "Failed adding new group to firestore", Toast.LENGTH_LONG).show();
        }
    });
}

UPDATE:更新: 获取字段值

空指针异常

获取数据

It looks like the issue is that you have created a document that is more nested than you intended, and includes the document id in the document itself.看起来问题在于您创建的文档比您预期的嵌套程度更高,并且在文档本身中包含了文档 ID。 You created something like this (which you can see in your Firestore screenshot, as well as the log output you posted):您创建了类似这样的内容(您可以在 Firestore 屏幕截图以及您发布的日志 output 中看到):

collection[docId] = {docId={group_name=Test}}

when I think you intended to create当我认为你打算创造

collection[docId] = {group_name=Test}

To fix this, you would just change document(key).set(update) to document(key).set(groupData) in CreateNewGroup .要解决此问题,您只需在CreateNewGroup中将document(key).set(update)更改为document(key).set(groupData)

There are several useful examples of how to set and update document data in theFirestore docs . Firestore 文档中有几个关于如何设置和更新文档数据的有用示例。

Alternately, if this is your intended document structure you would need to change how you retrieve group_name .或者,如果这是您想要的文档结构,则需要更改检索group_name的方式。

Instead of代替

String group = documentSnapshot.getString("group_name");

you would need something like this to first retrieve the nested map, then get the group_name attribute from it你需要这样的东西来首先检索嵌套的 map,然后从中获取group_name属性

String group = documentSnapshot.getData().get(key).get("group_name");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM