如何从 Firestore 获取订单 ID 并将其传递给我的适配器 class?

How can I get an order id from Firestore and pass it to my adaptor class?

我需要从 Firestore 获取订单 ID 并将该 ID 传递给我的查询,但我获取的订单 ID 是异步发生的。所以我不得不在 Firebase 回调方法中初始化我的适配器。问题是我的 onStart 和 onStop 方法正在侦听适配器,然后抛出 NullPointException。

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_to_cart);

        // Navigate to men section
        fromAddToCartToForHim = findViewById(R.id.fromAddToCartToForHim);
        fromAddToCartToForHim.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(AddToCart.this, HimActivity.class);
                startActivity(intent);
                finish();
            }
        });


        //Navigate to Women section
        fromAddToCartToForHer = findViewById(R.id.fromAddToCartToForHer);
        fromAddToCartToForHer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(AddToCart.this, WomenActivity.class);
                startActivity(intent);
                finish();
            }
        });


        // Navigate to Household section

        fromAddToCartToForHouseHold = findViewById(R.id.fromAddToCartToForHouseHold);
        fromAddToCartToForHouseHold.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(AddToCart.this, HouseHoldActivity.class);
                startActivity(intent);
                finish();
            }
        });


        // SetUpRecyclerView func

        setUpRecycleView();


    }


private void setUpRecycleView() {


        // GET CURRENT ORDER ID

        orderRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull @NotNull Task<QuerySnapshot> task) {
                if (task.isComplete()) {

                    QuerySnapshot snapshot = task.getResult();

                    assert snapshot != null;
                    for (DocumentSnapshot snapshots : snapshot.getDocuments()) {

                        String user_id = snapshots.getString("user_id");
                        Boolean status = snapshots.getBoolean("status");

                        if (user_id.equals(getUserId()) && !status) {

                            // User has existing Order
                            // Check if order is pending or completed

                            String orderId = snapshots.getId();

                            Query query = orderRef
                                    .document(orderId)
                                    .collection("orderlist")
                                    .orderBy("category").orderBy("priority", Query.Direction.ASCENDING);

                            FirestoreRecyclerOptions<OrderList> options = new FirestoreRecyclerOptions.Builder<OrderList>()
                                    .setQuery(query, OrderList.class)
                                    .build();


                            addToCartAdaptor = new AddToCartAdaptor(options);

                            recyclerView = findViewById(R.id.recyclerviewAddToCart);
                            recyclerView.setHasFixedSize(true);
                            recyclerView.setLayoutManager(new LinearLayoutManager(AddToCart.this));
                            recyclerView.setAdapter(addToCartAdaptor);
                        }
                    }
                }


            }
        });
    }



enter code here

 @Override
    protected void onStart() {
        super.onStart();
        addToCartAdaptor.startListening(); Error happens here
    }

    @Override
    protected void onStop() {   `enter code here`
        super.onStop();

        addToCartAdaptor.stopListening();
    }

这是我得到的错误

W/example.neptun: Accessing hidden method Lcom/msic/qarth/PatchStore;->createDisableExceptionQarthFile(Ljava/lang/Throwable;)Z (blacklist, JNI)
E/example.neptun: [qarth_debug:]  get PatchStore::createDisableExceptionQarthFile method fail.
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.neptune, PID: 2884
    java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.neptune.Adapters.AddToCartAdaptor.startListening()' on a null object reference
        at com.example.neptune.AddToCart.onStart(AddToCart.java:150)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1419)
        at android.app.Activity.performStart(Activity.java:7479)
        at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3454)
        at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:180)
        at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:165)
        at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:142)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2199)
        at android.os.Handler.dispatchMessage(Handler.java:112)
        at android.os.Looper.loop(Looper.java:216)
        at android.app.ActivityThread.main(ActivityThread.java:7625)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
I/Process: Sending signal. PID: 2884 SIG: 9

当您使用以下代码行时:

addToCartAdaptor = new AddToCartAdaptor(options);

在“onComplete()”方法中,这意味着它总是会在 onStart 之后 运行,因为从 orderRef 引用获取数据需要一些时间。您可以做的是在 onComplete() 方法之外创建(默认)Query、FirestoreRecyclerOptions 和 AddToCartAdaptor 对象,一旦您在回调中获得数据,只需使用您获得的数据更新“选项”对象从数据库。通过这种方式,您仅在“选项”对象可用时才将数据提供给它。

这也意味着您将永远不会再得到 NullPointerException,因为 addToCartAdaptor 已经初始化。