2011-10-28 6 views
7

関連情報を画面にダンプするためのアクティビティに例外を渡そうとしています。例外を小包として渡す

現在、私がバンドルを通してそれを渡す:それはそこに着くとき

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、バンドルの詳細を見ると、それは伝えています私には「例外」という名前のキーを持つパーセル化可能なオブジェクトが1つあります。

これはタイプと関係がありますが、私が間違っていることは理解できません。私はちょうど例外についての情報、画面への例外をダンプしたい。そのたびにすべての情報を文字列に集約する必要はありません。

答えて

14

:getStackTraceArrayはこのようになります

Intent intent = new Intent().setClass(this,ExceptionActivity.class) 
intent.putExtra("exception message", e.getMessage()); 
intent.putExtra("exception stacktrace", getStackTraceArray(e)); 
startActivity(intent); 

。しかし、私はより良い方法を見つけた、あなたは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(); 
2

クラスExceptionはParcelableインターフェイスを実装していません。アンドロイドが基本的なJavaの構造を壊していない限り、私はこれを認識しません。つまり、例外を小包としてバンドルに入れることはできません。

実行を新しいアクティビティに「渡す」場合は、新しいアクティビティに必要なものをまとめてください。たとえば、例外メッセージとスタックトレースを渡したいとします。あなたはので、このような何かをしたい:私は活動へのサービスからの例外を渡すための方法を探していたこの質問につまずい

private static String[] getStackTraceArray(Exception e){ 
    StackTraceElement[] stackTraceElements = e.getStackTrace(); 
    String[] stackTracelines = new String[stackTraceElements.length]; 
    int i =0; 
    for(StackTraceElement se : stackTraceElements){ 
    stackTraceLines[i++] = se.toString(); 
    } 
    return stackTraceLines; 
} 
+0

母は、私が想定していないはず。情報をアクティビティに渡すより良い方法はありますか? –

+0

make public class ParcelableException Exception implements Parcelable {...} – yorkw

+0

これに対処するために私の答えが更新されました。 –

関連する問題