Я пробовал методы отсоединения слушателей, такие как ListenerRegistration
или добавления активности на addSnapshotListener
, но ни одна из этих работ не работает.Я попытался удалить некоторые данные в моей базе данных, и она работает нормально, но когда я нажимаю кнопку «Назад», мое приложение выдает ошибку в строках, которые находятся внутри Слушателя.
РЕДАКТИРОВАТЬ: Просто дляпоясните, я пытался использовать ListenerRegistration
и добавление действия в addSnapshotListener
отдельно и все еще не работает.
ExpandedCartActivity
registration = query.addSnapshotListener(this, new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.e("DB_Error", e.toString());
return;
}
for (DocumentChange dc : queryDocumentSnapshots.getDocumentChanges()) {
DocumentSnapshot snapshot = dc.getDocument();
BasketProductsModel basketProductsModelList = snapshot.toObject(BasketProductsModel.class);
Map<String, String> prodImage = basketProductsModelList.getProductImage();
String prodName = basketProductsModelList.getProductName();
double productPrice = basketProductsModelList.getProductPrice();
double productCuttedPrice = basketProductsModelList.getProductCuttedPrice();
String productID = basketProductsModelList.getProductID();
int productQuantity = basketProductsModelList.getProductQuantity();
boolean isBargain = (boolean) snapshot.get("bargain.bargainStatus");
int oldIndex = dc.getOldIndex();
int newIndex = dc.getNewIndex();
switch (dc.getType()) {
case ADDED:
if (isBargain) {
long discountValue = (long) snapshot.get("bargain.discountValue");
double discount = (double) discountValue;
double discountPoint = discount / 100;
double dp = productPrice * discountPoint;
double newPrice = productPrice - dp;
basketProducts.add(new BasketProductsModel(prodImage, prodName, productQuantity, productPrice, newPrice, productID, storeID, UserID));
} else {
basketProducts.add(new BasketProductsModel(prodImage, prodName, productQuantity, productPrice, productCuttedPrice, productID, storeID, UserID));
}
break;
case MODIFIED:
if (isBargain) {
long discountValue = (long) snapshot.get("bargain.discountValue");
double discount = (double) discountValue;
double discountPoint = discount / 100;
double dp = productPrice * discountPoint;
double newPrice = productPrice - dp;
basketProducts.set(newIndex, new BasketProductsModel(prodImage, prodName, productQuantity, productPrice, newPrice, productID, storeID, UserID));
} else {
basketProducts.set(newIndex, new BasketProductsModel(prodImage, prodName, productQuantity, productPrice, productCuttedPrice, productID, storeID, UserID));
}
break;
case REMOVED:
basketProducts.remove(oldIndex);
break;
}
final NumberFormat cf1 = NumberFormat.getCurrencyInstance(new Locale("en", "PH"));
int prodQuantity = 0;
for (int r = 0; r < basketProducts.size(); r++) {
int prodQuan = basketProducts.get(r).getProductQuantity();
prodQuantity += prodQuan;
}
if (prodQuantity > 1) {
productquantityTotal.setText("Products: (" + prodQuantity + " items)");
} else {
productquantityTotal.setText("Product: (" + prodQuantity + " item)");
}
double subtotal = 0;
for (int d = 0; d < basketProducts.size(); d++) {
int prodQuan = basketProducts.get(d).getProductQuantity();
double pcp = basketProducts.get(d).getProductCuttedPrice();
double data = basketProducts.get(d).getProductPrice();
if (pcp == 0) {
double mult = data * prodQuan;
subtotal += mult;
} else {
double mult = pcp * prodQuan;
subtotal += mult;
}
}
coupon_text.setText("You are using coupon in this Order.");
button.setText("change");
redeem.setBackgroundColor(Color.parseColor("#7AC1FE"));
couponname.setVisibility(View.VISIBLE);
coupondiscount.setVisibility(View.VISIBLE);
final String productSubtotal = cf1.format(subtotal);
productPriceSubtotal.setText("Php " + productSubtotal);
final double finalSubtotal = subtotal;
db.collection("Baskets").document(UserID).collection("Store_Baskets").document(storeID).addSnapshotListener(new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.e("DB_Error", e.toString());
} else {
String couponId = documentSnapshot.get("couponID").toString();
if (couponId.equals("")) {
couponname.setVisibility(View.GONE);
coupondiscount.setVisibility(View.GONE);
saved.setVisibility(View.GONE);
redeem.setVisibility(View.VISIBLE);
productPriceSubtotal.setText(productSubtotal);
totalamount.setText(productSubtotal);
} else {
db.collection("Coupons").document(UserID).collection("Store_Coupons").document(couponId).addSnapshotListener(new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.e("DB_Error", e.toString());
} else {
CouponsModel model = documentSnapshot.toObject(CouponsModel.class);
String couponType = model.getCouponType();
int couponValue = model.getCouponValue();
boolean isUsed = model.isUsed();
if (!isUsed) {
if (couponType.equals("percent")) {
String couponVal = Integer.toString(couponValue);
coupondiscount.setText(couponVal + "% off");
double coupondouble = couponValue;
double percent = coupondouble / 100;
double Subtotalprice = finalSubtotal;
double discountedPrice = finalSubtotal * percent;
long rounded = Math.round(discountedPrice);
double TotalPrice = Subtotalprice - rounded;
String disPrice = cf1.format(rounded);
String ctotalprice = cf1.format(TotalPrice);
totalamount.setText(ctotalprice);
saved.setText("You will save " + disPrice + " on this Order");
} else if (couponType.equals("whole")) {
String couponVal = cf1.format(couponValue);
coupondiscount.setText(couponVal + " off");
double TotalPrice = finalSubtotal - couponValue;
String ctotalprice = cf1.format(TotalPrice);
totalamount.setText(ctotalprice);
saved.setText("You will save Php " + couponValue + " on this Order");
} else {
Log.e("DB_Error", "Coupon Data Error");
}
}
}
}
});
}
}
}
});
}
}
});
...
@Override
protected void onDestroy() {
super.onDestroy();
if (registration!= null) {
registration.remove();
registration = null;
}
}
@Override
protected void onStop() {
super.onStop();
baseAdapter.stopListening();
if (registration!= null) {
registration.remove();
registration = null;
}
}
Тогда вот исключение
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
at com.dreamakers.coonna.Activity.ExpandedCartActivity$3$1.onEvent(ExpandedCartActivity.java:353)
at com.dreamakers.coonna.Activity.ExpandedCartActivity$3$1.onEvent(ExpandedCartActivity.java:347)
at com.google.firebase.firestore.DocumentReference.lambda$addSnapshotListenerInternal$2(com.google.firebase:firebase-firestore@@17.1.2:541)
at com.google.firebase.firestore.DocumentReference$$Lambda$3.onEvent(com.google.firebase:firebase-firestore@@17.1.2)
at com.google.firebase.firestore.util.ExecutorEventListener.lambda$onEvent$0(com.google.firebase:firebase-firestore@@17.1.2:42)
at com.google.firebase.firestore.util.ExecutorEventListener$$Lambda$1.run(com.google.firebase:firebase-firestore@@17.1.2)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5637)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
Что было от:
String couponId = documentSnapshot.get("couponID").toString();