我正在嘗試從 firestore 中的字串欄位 group_name 檢索值,但我收到 NullPointerException,因為該值沒有被檢索并添加到陣列串列中。所以陣列串列是空的。我正在嘗試在 OnCreateView 中獲取資料,因為我正在處理片段。添加資料非常有效(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();
}
});
}
更新:



uj5u.com熱心網友回復:
看起來問題在于您創建了一個比您預期的嵌套更多的檔案,并且在檔案本身中包含了檔案 ID。您創建了這樣的內容(您可以在 Firestore 螢屏截圖以及您發布的日志輸出中看到):
collection[docId] = {docId={group_name=Test}}
當我認為你打算創造
collection[docId] = {group_name=Test}
要解決此問題,您只需更改document(key).set(update)為document(key).set(groupData)in CreateNewGroup。
Firestore 檔案中有幾個關于如何設定和更新檔案資料的有用示例。
或者,如果這是您想要的檔案結構,您將需要更改檢索group_name.
代替
String group = documentSnapshot.getString("group_name");
您需要這樣的東西來首先檢索嵌套地圖,然后從中獲取group_name屬性
String group = documentSnapshot.getData().get(key).get("group_name");
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/375485.html
標籤:爪哇 安卓 谷歌云firestore
