Search code examples
androidandroid-fragmentsandroid-bundle

Bundle.getString() returning null?


I'm trying to pass json through a string in a bundle. The string gets loaded into the bundle just fine. but it looks like it is getting the wrong bundle.

in onCreate of one class:

    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);

inside my fragment:

 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);

}

Solution

  • you must create instance inside of fragment like this

    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);
    
        }
    }
    

    And use like this inside your activity

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