【问题标题】:Explicit Intent Errors while working with putExtra()使用 putExtra() 时的显式意图错误
【发布时间】:2017-09-21 04:21:10
【问题描述】:

假设应用程序具有三个活动,即 A1、A2、A3:

A1 调用 A2 并在其 Intent“值”中附加一个值

Intent i=new Intent(A1.this,A2.class);
i.putExtra("value",editTextVal); //editTextVal is got from an editText during Runtime

其中 A2 接受来自 A1 的附加值并将其存储在“样本”中:

sample=getIntent().getExtra().getString("value");

现在控件从 A2 转到 A3。即,A2 意图到 A3,现在当 A3 调用 Activity A2 时会发生错误,因为 A2 有 .getExtra() 试图从 Intent 获取附加数据,因为A3中使用的Intent没有.putExtra()就是这个,

Intent i3=new Intent(A3.this,A2.class);

所以发生了运行时错误..帮我解决这个问题..

【问题讨论】:

  • 把你的堆栈跟踪放在这里
  • 使用它就像 Bundle b=getIntent().getExtra(); if(b!=null){ }

标签: android android-intent parameter-passing


【解决方案1】:

当您从 A3 移动到 A2 时,A2 活动会搜索捆绑对象,但由于您没有将任何值从 A3 传递到 A2,因此会出现空点异常 阻止这种情况的一种方法是设置一个标志(静态变量),并在您对 FLAG 的 A2 活动检查值(如果 FLAG==1 尝试获取 Bundle 对象)进行从 A1 到 A2 的转换时为其分配任何值,例如 1。每当您从 A2 移动时,请确保将 FLAG 更改为 1 以外的其他值

      //Declare a Variable FLAG in A1 as 
      public static int FLAG;

      // For transition from A1 to A2
       Intent I =new Intent(A1.this,A2.class);
       I.putExtras("Key","Value");
       FLAG=1;
       startActivity(I);

       //on your A2 activity 
       if(A1.FLAG==1)
       {
          Bundle extras=getIntent().getExtras();
          String Value=extras.getString("Key");
       }

        //When you make a transition to A3

       Intent i1=new Intent(A1.this,A2.class);
       A.FLAG=2;
       startAcitivy(i1);

【讨论】:

    【解决方案2】:
        if(getIntent().hasExtra("value")) {
            sample=getIntent().getStringExtra("value");
        }
    
        /* while using sample check for null
    
         */
        if(!TextUtils.isEmpty(sample)) {
            // use sample here
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-05
      • 1970-01-01
      • 2014-06-02
      • 2013-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多