当我需要片段中的上下文时,我不会在firestore方法中使用getActivity(),但是有时候 firestore代码崩溃并给我NullPointer。 ..要修复它,我尝试使用:
.addSnapshotListener(getActivity(), new Event..)
当我添加getActivity()
时(如下例所示),它总是 NullPointer
public class HomeFragment extends Fragment {
private FirebaseFirestore firebaseFirestore;
private FirebaseAuth mAuth;
private TextView demand;
private TextView design;
public HomeFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
firebaseFirestore = FirebaseFirestore.getInstance();
mAuth = FirebaseAuth.getInstance();
demand = (TextView) view.findViewById(R.id.home_production_demand_text_count);
design = (TextView) view.findViewById(R.id.home_production_design_text_count);
return view;
}
// @Override
// public void onAttach(Context context) {
// super.onAttach(context);
// }
@Override
public void onStart() {
super.onStart();
if (mAuth.getCurrentUser() != null) {
// retrieve likes count
firebaseFirestore.collection("Demand").addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if (!documentSnapshots.isEmpty()) {
int count = documentSnapshots.size(); // count id
demand.setText(count);
}
}
});
// retrieve likes count
firebaseFirestore.collection("Design").addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if (!documentSnapshots.isEmpty()) {
int count = documentSnapshots.size(); // count id
design.setText(count);
}
}
});
}
}
}
当我使用getActivity()
时,此片段总是崩溃,而当我不使用getActivity()
时,有时会崩溃
该如何解决?