空指针异常将数据从活动传递到Fragment

时间:2014-12-02 10:26:47

标签: android android-activity android-fragments android-fragmentactivity

我在MainActivity页面中有url值,我需要将此url值从ACtivity传递给Fragment。但是当我点击按钮时,我在String url=getArguments().getString("btn_url");

的行上获得了空例外

的活动:

 Fragment fragment=new About();                             
        if (fragment != null) {

     FragmentTransaction transaction = getFragmentManager().beginTransaction();
       transaction.replace(R.id.frame_container, fragment, "TAG_FRAGMENT");
        transaction.addToBackStack(null);
        transaction.commit(); 

          Bundle bundle=new Bundle();
          bundle.putString("btn_url", URL);
About fragobj=new About();
     fragobj.setArguments(bundle);
    }

片段:

String url=getArguments().getString("btn_url");

1 个答案:

答案 0 :(得分:2)

设置片段参数后需要提交。 将您的代码更改为:

About fragobj=new About();    
Bundle bundle=new Bundle();
bundle.putString("btn_url", URL);        
fragobj.setArguments(bundle);
getFragmentManager().beginTransaction();
.replace(R.id.frame_container, fragobj, "TAG_FRAGMENT");
.addToBackStack(null);
.commit();