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

Asked

Viewed 65 times

2

I have an Activity that is added a data in Jsonobjetct. And as seen in the following code, I take it as a string, but, my doubt, as I by this Jsonobject in the fragment so that I can work with it, as Json?

Follows code from Activity:

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

1 answer

3


This is the most appropriate way to do it, as your Activity will not need to know the keys that your Fragment needs and you require it to enter the correct parameters.

In the case of your Objectjson you may need to convert it to String to put in the Bundle and Fragment recovered from the String pro Object. I advise you to already create an object and convert the json into 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 will be able to recover the saved objects in this way:

getArguments().getString("someString", 0);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.