如何将JSONArray从一个片段传递到另一个片段

时间:2017-04-15 06:48:42

标签: android arrays json android-fragments

我正在尝试将JSONArray从一个片段传递到另一个片段,但我得到的是NullPointerException。

片段1

JSONArray bankarray = jsonobject1.getJSONArray("banks");
Fragment f = new SendMoneyRecipientFragment();
Bundle b = new Bundle();
b.putString("banklist", banks);
f.setArguments(b);

片段2

getArguments()的getString(" banklist&#34);

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您可以使用Activity。例如: 片段1

public class Fragment1 extends Fragment {

    private String mJSON;
    private Context mContext;

    public static Fragment1 instance() {
        return new Fragment1();
    }

    @Override
public void onAttach(Context context) {
    super.onAttach(context);
    try {
        mContext = (IContext) context;
    } catch (ClassCastException e) {
        throw new ClassCastException(context.toString() + " must implement " + IContext.class.getName());
    }
}

    //... some code to fetch JSON and set it to mJSON


    private void onSomeButtonClick() {
        if (mContext != null) {
            mContext.showFragment2(mJSON);
        }
    }
}

Fragment2

public class Fragment2 extends Fragment {
    private static final String KEY_JSON = "key_json";

    public static Fragment2 instance(String json) {
        Bundle args = new Bundle();
        args.putString(KEY_JSON, json);
        Fragment2 f = new Fragment2();
        f.setArguments(args);
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_layout, container, false);
    }

    @Override
    public void onViewCreated(View root, Bundle savedInstanceState) {
        super.onViewCreated(root, savedInstanceState);
        String json = getArguments().getString(KEY_JSON);

        //do whatever you want with json
    }
}

IContext

public interface IContext {
    void showFragment2(String json);
}

您的活动

public class YourActivity extends AppCompatActivity implements IContext {
    //... some code to initialize - onCreate() ...


    @Override
    public void showFragment2(String json) {
        Fragment fr2 = Fragment2.instance(json);
        FragmentTransaction tr = getSupportFragmentManager().beginTransaction()
            .replace(R.id.fragment_container, fr2, fr2.getClass().getName());
        //add to backstack if need tr.addToBackStack(null);
        tr.commitAllowingStateLoss();
    }
}