如何将异常传递给另一个活动?

时间:2012-09-19 12:07:56

标签: android

我有class,不会延伸Activity。在该课程中,我使用try-catch块来捕捉exceptions。如何将该块中捕获的任何异常(Exception e)传递给另一个Activity?我的应用程序使用boolean flag进行检查以显示toast message。但是如何将此消息传递给另一个活动?

public class AgAppHelperMethods   {

  private static AgAppHelperMethods instance = null;
  static boolean flag=true;

 public static   String[][] AgAppXMLParser( String parUrl) {



    String _node,_element;
    String[][] xmlRespone = null;
    try {
  String url = www.xyz.com
            URL finalUrl = new URL(url);


    catch (Exception e)
    {
      flag=false;
      Log.e( "CONNECTION ERROR  SERVER NOT RESPONDING", e);
    } 


          public class LoginScreen extends Activity implements Serializable {


public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    setContentView(R.layout.agapplogin);


       btnClear.setOnClickListener(new OnClickListener() {
        public void onClick(View v)

        {
            postLoginData();
        }

    });


           public void postLoginData()

{
               xmlRespone = AgAppHelperMethods.AgAppXMLParser( url);

        if(!AgAppHelperMethods.flag)
        {
             Toast.makeText(getApplicationContext(), "Error  server 
    not responding " , Toast.LENGTH_SHORT).show();
             myProgressDialog.dismiss();
        }

2 个答案:

答案 0 :(得分:1)

 catch (Exception e) {        
    flag=false;
    Log.e( "CONNECTION ERROR  SERVER NOT RESPONDING", e);

    String theException = e.getMessage();

    Bundle b = new Bundle();        
    b.putString("Exception", theException); //or you can replace theException with a custom message

    Intent nextActivity = new Intent(MyActivity.this, NewActivity.class);
    nextActivity.putExtras(b);
    startActivity(nextActivity); 
    }   

您可以使用下一个活动的onCreate方法接收

    Bundle b = getIntent().getExtras();
    String error = b.getString("Exception");
    Toast.makeText(NewActivity.this, error, Toast.LENGTH_SHORT).show();

希望这会有所帮助!!

答案 1 :(得分:0)

使用Intent extras将额外数据传递给另一个Activity:

见这里:How do I get extra data from intent on Android? 在这里:http://www.vogella.com/articles/AndroidIntent/article.html