【问题标题】:Not able to pass data from activity to fragment无法将数据从活动传递到片段
【发布时间】:2018-03-07 06:37:33
【问题描述】:

我正在开发一个应用程序,其中有一个 Activity,最初加载一个 Fragment。我在活动中得到 IMEI No, Latitude, Longitude,我将该数据传递到片段中,并在片段中获取该数据,但是当我获取数据时出现空指针异常。

最初我的帐户活动会加载注册片段,并且我正在将数据从帐户活动发送到注册片段

// 发送数据的活动代码

//在Account Activity中设置SignUp Fragment

changeFragments(new SignupFragment());

// 现在调用函数 GeoLocation 并将其发送到注册片段

public void GeoLocation() {

    Bundle bundle = new Bundle();
    bundle.putString("imei_no", imei_number);
    bundle.putString("lat",latitude.toString());
    bundle.putString("long",longitude.toString());
    bundle.putString("postal_code",postalCode);

    SignupFragment fragObj = new SignupFragment();
    fragObj.setArguments(bundle);
} 

// Now Sign Up Fragment > 我正在获取我调用 Api 的这些字段

private void callApi() {

    String imei_no = getArguments().getString("imei_no");
    String  latitude  = getArguments().getString("lat");
    String longitude = getArguments().getString("long");
    String postal_code = getArguments().getString("postal_code");
}

我在这里得到空指针异常。

【问题讨论】:

    标签: android class android-fragments


    【解决方案1】:
    changeFragments(fragobj);
    

    改变这一行,因为如果你当时使用新的 SingupFragment 它会创建新的对象

    【讨论】:

      【解决方案2】:

      你应该传递片段的实例而不是创建新的实例:-

        public void GeoLocation() {
      
            Bundle bundle = new Bundle();
                  bundle.putString("imei_no", imei_number);
                  bundle.putString("lat",latitude.toString());
                  bundle.putString("long",longitude.toString());
                  bundle.putString("postal_code",postalCode);
      
                  SignupFragment fragobj = new SignupFragment();
                  fragobj.setArguments(bundle);
      
        changeFragments(fragobj);
          } 
      

      这里我调用 GeoLocation 中的 changeFragments() 方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多