我试图将异常传递给意图将相关信息转储到屏幕的活动.
目前我通过捆绑传递:
try { this.listPackageActivities(); } catch (Exception e) { Intent intent = new Intent().setClass(this,ExceptionActivity.class).putExtra("Exception",e); startActivity(intent); }
但当它到达那里时:
if (!(this.bundle.getParcelable("Exception") != null)) throw new IndexOutOfBoundsException("Index \"Exception\" does not exist in the parcel." + "/n" + "Keys: " + this.bundle.keySet().toString());
抛出这个甜蜜的异常但是当我查看keySet和bundle的详细信息时,它会告诉我有一个可以使用名为“Exception”的密钥的可分配对象.
我知道这与类型有关,但我不明白我做错了什么.我只想转储有关异常的信息,屏幕上的任何异常.有没有办法做到这一点,而不必每次都将所有信息压缩成一个字符串?
解决方法
当我在寻找将异常从服务传递到活动的方法时,我偶然发现了这个问题.但是,我发现了一个更好的方法,你可以使用Bundle类的putSerializable()方法.
加上:
Throwable exception = new RuntimeException("Exception"); Bundle extras = new Bundle(); extras.putSerializable("exception",(Serializable) exception); Intent intent = new Intent(); intent.putExtras(extras);
要检索:
Bundle extras = intent.getExtras(); Throwable exception = (Throwable) extras.getSerializable("exception"); String message = exception.getMessage();