How to send a json from an Activity to a Fragment?

2

I have an activity that adds a die in JsonObjetct. And as seen in the following code, I take it as string, but, my doubt, how do I by this JsonObject in the fragment so I can work with it, as Json?

Follow the Activity code:

.........
    objectJson = SharedPreferenceHelper.getScheduling(this);
    inicializeSetting(savedInstanceState);

    btn_1 = (ToggleButton)findViewById(R.id.tglSearch1);
    btn_1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            btn_1.setChecked(true);
            btn_2.setChecked(false);
            objectJson.addProperty("type", 0);

        }
    });
    btn_2 = (ToggleButton)findViewById(R.id.tglSearch2);
    btn_2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            btn_1.setChecked(false);
            btn_2.setChecked(true);
            objectJson.addProperty("type", 1);
        }
    });

    btnContinuar = (Button)findViewById(R.id.btnGoSearch);
    btnContinuar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SearchAskListFragment fragment = new SearchAskListFragment();

            Bundle bundle = new Bundle();
            bundle.putString("json", objectJson.toString());
            fragment.setArguments(bundle);

            getSupportFragmentManager().beginTransaction()
                    .add(R.id.containerLinear, fragment)
                    .commit();
            getSupportFragmentManager().executePendingTransactions();
           // Routes.open(getApplicationContext(),URIs.SearchAskFragment());
        }
    });
    
asked by anonymous 16.03.2017 / 18:17

1 answer

3

This is the best way to do it, because your activity will not need to know the keys that your fragment needs and you have to instantiate it with the correct parameters.

In the case of your ObjectJson you may need to convert it to String to place in the bundle and in the fragment recovered from the String pro Object. I advise you to already create an object and convert the json in it to easily transit through activities and fragments.

public static MyFragment newInstance(String param) {
    MyFragment myFragment = new MyFragment();

    Bundle args = new Bundle();
    args.putString("someString", param);
    myFragment.setArguments(args);

    return myFragment;
}

You were able to recover the objects saved this way:

getArguments().getString("someString", 0);
    
16.03.2017 / 18:56