tv-casting-app fix CloseCommissioningWindow upon unexpected CDC Commi… (#35984)

diff --git a/examples/tv-casting-app/android/App/app/src/main/java/com/matter/casting/ConnectionExampleFragment.java b/examples/tv-casting-app/android/App/app/src/main/java/com/matter/casting/ConnectionExampleFragment.java
index fc3ba6c..f711096 100644
--- a/examples/tv-casting-app/android/App/app/src/main/java/com/matter/casting/ConnectionExampleFragment.java
+++ b/examples/tv-casting-app/android/App/app/src/main/java/com/matter/casting/ConnectionExampleFragment.java
@@ -29,6 +29,7 @@
 import android.widget.TextView;
 import androidx.annotation.Nullable;
 import androidx.fragment.app.Fragment;
+import androidx.fragment.app.FragmentActivity;
 import com.R;
 import com.matter.casting.core.CastingPlayer;
 import com.matter.casting.support.CommissionerDeclaration;
@@ -208,36 +209,41 @@
                       Log.i(TAG, "CastingPlayer CommissionerDeclaration message received: ");
                       cd.logDetail();
 
-                      getActivity()
-                          .runOnUiThread(
-                              () -> {
+                      FragmentActivity activity = getActivity();
+                      // Prevent possible NullPointerException. This callback could be called when
+                      // this Fragment is not attached to its host activity or when the fragment's
+                      // lifecycle is not in a valid state for interacting with the activity.
+                      if (activity != null && !activity.isFinishing()) {
+                        activity.runOnUiThread(
+                            () -> {
+                              connectionFragmentStatusTextView.setText(
+                                  "CommissionerDeclaration message received from Casting Player: \n\n");
+                              if (cd.getCommissionerPasscode()) {
+
+                                displayPasscodeInputDialog(activity);
+
                                 connectionFragmentStatusTextView.setText(
-                                    "CommissionerDeclaration message received from Casting Player: \n\n");
-                                if (cd.getCommissionerPasscode()) {
-
-                                  displayPasscodeInputDialog(getActivity());
-
+                                    "CommissionerDeclaration message received from Casting Player: A passcode is now displayed for the user by the Casting Player. \n\n");
+                              }
+                              if (cd.getCancelPasscode()) {
+                                if (useCommissionerGeneratedPasscode) {
                                   connectionFragmentStatusTextView.setText(
-                                      "CommissionerDeclaration message received from Casting Player: A passcode is now displayed for the user by the Casting Player. \n\n");
+                                      "CastingPlayer/Commissioner-Generated passcode connection attempt cancelled by the CastingPlayer/Commissioner user. \n\nRoute back to exit. \n\n");
+                                } else {
+                                  connectionFragmentStatusTextView.setText(
+                                      "Connection attempt cancelled by the CastingPlayer/Commissioner user. \n\nRoute back to exit. \n\n");
                                 }
-                                if (cd.getCancelPasscode()) {
-                                  if (useCommissionerGeneratedPasscode) {
-                                    connectionFragmentStatusTextView.setText(
-                                        "CastingPlayer/Commissioner-Generated passcode connection attempt cancelled by the CastingPlayer/Commissioner user. \n\nRoute back to exit. \n\n");
-                                  } else {
-                                    connectionFragmentStatusTextView.setText(
-                                        "Connection attempt cancelled by the CastingPlayer/Commissioner user. \n\nRoute back to exit. \n\n");
-                                  }
-                                  if (passcodeDialog != null && passcodeDialog.isShowing()) {
-                                    passcodeDialog.dismiss();
-                                  }
+                                if (passcodeDialog != null && passcodeDialog.isShowing()) {
+                                  passcodeDialog.dismiss();
                                 }
-                                if (cd.getErrorCode() != CommissionerDeclaration.CdError.noError) {
-                                  commissionerDeclarationErrorTextView.setText(
-                                      "CommissionerDeclaration error from CastingPlayer: "
-                                          + cd.getErrorCode().getDescription());
-                                }
-                              });
+                              }
+                              if (cd.getErrorCode() != CommissionerDeclaration.CdError.noError) {
+                                commissionerDeclarationErrorTextView.setText(
+                                    "CommissionerDeclaration error from CastingPlayer: "
+                                        + cd.getErrorCode().getDescription());
+                              }
+                            });
+                      }
                     }
                   };
 
diff --git a/examples/tv-casting-app/linux/simple-app-helper.cpp b/examples/tv-casting-app/linux/simple-app-helper.cpp
index 4bdf660..f354aa0 100644
--- a/examples/tv-casting-app/linux/simple-app-helper.cpp
+++ b/examples/tv-casting-app/linux/simple-app-helper.cpp
@@ -289,7 +289,7 @@
                         kDesiredEndpointVendorId);
     }
 
-    ChipLogProgress(AppServer, "simple-app-helper.cpp::ConnectionHandler(): Getting endpoints avaiable for demo interactions");
+    ChipLogProgress(AppServer, "simple-app-helper.cpp::ConnectionHandler(): Getting endpoints available for demo interactions");
     std::vector<matter::casting::memory::Strong<matter::casting::core::Endpoint>> endpoints = castingPlayer->GetEndpoints();
     LogEndpointsDetails(endpoints);
 
diff --git a/examples/tv-casting-app/tv-casting-common/core/CommissionerDeclarationHandler.cpp b/examples/tv-casting-app/tv-casting-common/core/CommissionerDeclarationHandler.cpp
index c89b899..a54d101 100644
--- a/examples/tv-casting-app/tv-casting-common/core/CommissionerDeclarationHandler.cpp
+++ b/examples/tv-casting-app/tv-casting-common/core/CommissionerDeclarationHandler.cpp
@@ -38,18 +38,24 @@
     return sCommissionerDeclarationHandler_;
 }
 
-// TODO: In the following PRs. Implement setHandler() for CommissionerDeclaration messages and expose messages to higher layers for
-// Linux, Android and iOS.
 void CommissionerDeclarationHandler::OnCommissionerDeclarationMessage(
     const chip::Transport::PeerAddress & source, chip::Protocols::UserDirectedCommissioning::CommissionerDeclaration cd)
 {
-    ChipLogProgress(AppServer,
-                    "CommissionerDeclarationHandler::OnCommissionerDeclarationMessage(), calling CloseCommissioningWindow()");
-    // Close the commissioning window. Since we recived a CommissionerDeclaration message from the Commissioner, we know that
-    // commissioning via AccountLogin cluster failed. We will open a new commissioningWindow prior to sending the next
-    // IdentificationDeclaration Message to the Commissioner.
-    chip::Server::GetInstance().GetCommissioningWindowManager().CloseCommissioningWindow();
-    support::ChipDeviceEventHandler::SetUdcStatus(false);
+    ChipLogProgress(AppServer, "CommissionerDeclarationHandler::OnCommissionerDeclarationMessage()");
+
+    // During UDC with CastingPlayer/Commissioner-Generated Passcode, the Commissioner responds with a CommissionerDeclaration
+    // message with CommissionerPasscode set to true. The CommissionerPasscode flag indicates that a Passcode is now displayed for
+    // the user by the CastingPlayer /Commissioner. With this CommissionerDeclaration message, we also know that commissioning via
+    // AccountLogin cluster has failed. Therefore, we close the commissioning window. We will open a new commissioning window prior
+    // to sending the next/2nd IdentificationDeclaration message to the Commissioner.
+    if (cd.GetCommissionerPasscode())
+    {
+        ChipLogProgress(AppServer,
+                        "CommissionerDeclarationHandler::OnCommissionerDeclarationMessage(), calling CloseCommissioningWindow()");
+        // Close the commissioning window.
+        chip::Server::GetInstance().GetCommissioningWindowManager().CloseCommissioningWindow();
+        support::ChipDeviceEventHandler::SetUdcStatus(false);
+    }
 
     // Flag to indicate when the CastingPlayer/Commissioner user has decided to exit the commissioning process.
     if (cd.GetCancelPasscode())
@@ -57,6 +63,9 @@
         ChipLogProgress(AppServer,
                         "CommissionerDeclarationHandler::OnCommissionerDeclarationMessage(), Got CancelPasscode parameter, "
                         "CastingPlayer/Commissioner user has decided to exit the commissioning attempt. Connection aborted.");
+        // Close the commissioning window.
+        chip::Server::GetInstance().GetCommissioningWindowManager().CloseCommissioningWindow();
+        support::ChipDeviceEventHandler::SetUdcStatus(false);
         // Since the CastingPlayer/Commissioner user has decided to exit the commissioning process, we cancel the ongoing
         // connection attempt without notifying the CastingPlayer/Commissioner. Therefore the
         // shouldSendIdentificationDeclarationMessage flag in the internal StopConnecting() API call is set to false. The
@@ -65,12 +74,7 @@
         // and user 2 might be controlling the CastingPlayer/Commissioner TV.
         CastingPlayer * targetCastingPlayer = CastingPlayer::GetTargetCastingPlayer();
         // Avoid crashing if we recieve this CommissionerDeclaration message when targetCastingPlayer is nullptr.
-        if (targetCastingPlayer == nullptr)
-        {
-            ChipLogError(AppServer,
-                         "CommissionerDeclarationHandler::OnCommissionerDeclarationMessage() targetCastingPlayer is nullptr");
-        }
-        else
+        if (targetCastingPlayer != nullptr)
         {
             CHIP_ERROR err = targetCastingPlayer->StopConnecting(false);
             if (err != CHIP_NO_ERROR)
@@ -82,6 +86,11 @@
                     err.Format());
             }
         }
+        else
+        {
+            ChipLogError(AppServer,
+                         "CommissionerDeclarationHandler::OnCommissionerDeclarationMessage() targetCastingPlayer is nullptr");
+        }
     }
 
     if (mCmmissionerDeclarationCallback_)