Bundle.getString()返回空值?

时间:2019-01-06 07:10:16

标签: android android-fragments android-bundle

我正在尝试通过捆绑中的字符串传递json。该字符串被加载到捆绑包中就好了。但看起来好像得到了错误的捆绑包。

在一个类的onCreate中:

    if(intent!=null){

        jsonString = intent.getStringExtra(this.getBaseContext().getResources().getString(R.string.recipe_detail_json));

        //prints the string just fine here
        System.out.println(jsonString);

        Bundle bundle = new Bundle();
        bundle.putString("RECIPE_DETAIL_JSON",jsonString);
        srdFragment= new SelectRecipeDetailFragment();
        srdFragment.setArguments(bundle);
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.recipe_list_step_container, srdFragment).commit();

    }

    setContentView(R.layout.select_a_recipe_step);

在我的片段内:

 private String jsonString;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bundle bundle = getArguments();
    jsonString = bundle.getString("RECIPE_DETAIL_JSON");

    //this string prints null
    System.out.println(jsonString);

}

2 个答案:

答案 0 :(得分:1)

您必须像这样在片段内部创建实例

public class SelectRecipeDetailFragment extends Fragment{

   public static SelectRecipeDetailFragment newInstance(String jsonString) {
         SelectRecipeDetailFragment frag = new SelectRecipeDetailFragment();
          Bundle args = new Bundle();
          args.putString("RECIPE_DETAIL_JSON", jsonString);
          frag.setArguments(args);
          return frag;
   }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        jsonString = bundle.getString("RECIPE_DETAIL_JSON");

        //this string prints null
        System.out.println(jsonString);

    }
}

并在活动中像这样使用

 getSupportFragmentManager().beginTransaction()
            .replace(R.id.recipe_list_step_container, SelectRecipeDetailFragment.newInstance(jsonString).commit();

答案 1 :(得分:0)

在片段

中使用它
<xsl:variable name="var1" select="DEF"/>    
<frequency myAttr="ABC"+$var1 >    
     <xsl:value-of select="frequency"/>    
</frequency>