【发布时间】:2022-01-12 12:19:50
【问题描述】:
我正在尝试从 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();
}
});
}
【问题讨论】:
-
你为什么要在 onCreate 中这样做?如果这是一个片段,请使用 onViewCreated
-
问题是“group_name”字段的值没有被添加到组列表中,所以它保持为空。这会导致 NullPointerException。所以不,这不能回答我的问题。
-
Oncreate 通常不是问题。
-
@a_local_nobody 我添加了截图以更好地解释问题
标签: java android google-cloud-firestore