简体   繁体   中英

Android: Why Bundle putExtras doesn't work?

I know this is a stupid question, but problems happen randomly, so annoying! that is I found sometime Bundle putExtras() doesn't work very well(sometimes it works sometimes it doesn't). The bundle i received always only get one value:

for example,here i want to pass four string value to a fragment, here's the code:

Bundle license = new Bundle();
license.putString(LICENSE_1, license_1);
license.putString(LICENSE_2, license_2);
license.putString(LICENSE_3, license_3);
license.putString(LICENSE_ADD, license_add);
DialogFragment mFragment = new WatchOptionsDialog();
mFragment.setArguments(license);
mFragment.show(getActivity().getFragmentManager(),"tag");

at the top of this fragment I defined

public static final String LICENSE_1 = "";
public static final String LICENSE_2 = "";
public static final String LICENSE_3 = "";
public static final String LICENSE_ADD = "";

and the value of four string i wanna pass is "5", "6", "7", "8"

and in another fragment, i receive the bundle as this

Bundle license = getArguments();
String license_1 = license.getString(FragmentMovieInfo.LICENSE_1);
String license_2 = license.getString(FragmentMovieInfo.LICENSE_2);
String license_3 = license.getString(FragmentMovieInfo.LICENSE_3);
String license_add = license.getString(FragmentMovieInfo.LICENSE_ADD);

Log.v("license_1", license_1);
Log.v("license_2", license_2);
Log.v("license_3", license_3);
Log.v("license_add", license_add);

and the problems is all the value i got is four "8". as followed:

license_1   8
license_2   8
license_3   8
license_add 8

It happens many times when i use bundle, I only get the last value. why is that? is there any mistake with the code?

The problem is that you have defined all of your keys ( LICENSE_1 , LICENSE_2 , etc) as an empty string. Thus all of your keys are the exact same.

Methods such as putString() take two arguments- a key and a value. A Bundle is really just a map of key-value pairs. If all of your keys are the same, they all will map to the same values.

Use should use other values, eg:

public static final String LICENSE_1 = "LICENSE_1";
public static final String LICENSE_2 = "LICENSE_2";
public static final String LICENSE_3 = "LICENSE_3";
public static final String LICENSE_ADD = "LICENSE_ADD";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM