【问题标题】:Stop startActivity(intent) when going in catch block from another class从另一个类进入 catch 块时停止 startActivity(intent)
【发布时间】:2018-01-19 13:21:19
【问题描述】:

我正在开发一个 Android Xamarin 应用程序,其中我有一个带有按钮的活动。按钮中的一些代码是这样的:

fsp_SellDet_New_ByItemID fsp_SellDet_New_ByItemID = new fsp_SellDet_New_ByItemID(this);
            fsp_SellDet_New_ByItemID.ExecuteNonQuery(_SellID,
                                                     _ItemID,
                                                     _PodID,
                                                     _ItemSellQty,
                                                     _ItemPrice,
                                                     _ItemPricePer,
                                                     -_BaseDiscount,
                                                     -_AdditionalDiscount,
                                                     _ItemSum,
                                                     _ItemVAT,
                                                     _ItemCode,
                                                     _ItemShortName,
                                                     _ItemBrand,
                                                     _ItemIssue);
            Intent i = new Intent(this, typeof(SellDet));
            StartActivity(i);
            Finish();

我的问题是,在 ExecuteNonQuery 方法中,我在 try 和 catch 块中处理了异常,如下所示:

catch (Exception ex)
        {
            _dlgAlert = new AlertDialog.Builder(this).Create();
            _dlgAlert.SetMessage(ex.Message);
            _dlgAlert.SetTitle(Resources.GetString(Resource.String.Error));
            _dlgAlert.SetButton("OK", delegate { });
            _dlgAlert.Show();
            return;
        }

即使我使用“return;”,Android 仍然会打开下一个活动,所以我无法真正看到异常是什么,因为当 AlertDialog 出现时,下一个活动已经打开。

你能给我一些关于如何制作它的建议吗,所以如果我在 ExecuteNonQuery 方法中收到异常,会弹出一个 AlertDialog 并且它不会进入下一个活动。

或者你能告诉我怎么做,这样你就必须在 alertDialog 上按“OK”,然后它就会进入 activty。请记住,AlertDialog 在新创建的类的 executeNonQuery 方法中,而不是在按钮方法中。..

提前谢谢你

【问题讨论】:

    标签: c# android exception xamarin


    【解决方案1】:

    有很多方法可以解决这个问题。没有特别的顺序(如果您需要查看其中任何一个的编码示例,请告诉我):

    1. 不要在ExecuteNonQuery() 中捕获异常,而是在调用方法中捕获它

    2. ExecuteNonQuery() 返回一个布尔值,如果发生异常则返回false,否则返回true。然后在您的StartActivity 代码周围添加if 检查

    3. Action 传递给您的ExecuteNonQuery(),它将在您传递给_dlgAlert.SetButton("OK", delegate { /* Passed in Action executes here */ }); 的空委托中运行,Action 将包含您的StartActvity 代码

      李>

    【讨论】:

      猜你喜欢
      • 2014-04-16
      • 1970-01-01
      • 1970-01-01
      • 2019-02-21
      • 1970-01-01
      • 2011-08-31
      • 1970-01-01
      • 2021-10-23
      • 2021-08-16
      相关资源
      最近更新 更多