实例:
从MainActivity通过intent将Test类的对象传递给OtherActivity。
MainActivity代码:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Test test = new Test(); test.setValue("aaaaaaaa"); Intent intent = new Intent(MainActivity.this, OtherActivity.class); intent.putExtra("test", test); startActivity(intent); }OtherActivity代码:
@Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); Intent intent = getIntent(); Test test = intent.getParcelableExtra("test"); System.out.println(test.getValue()); }Test代码:
public class Test implements Parcelable{ private JSONObject mJson; public static final Parcelable.CreatorCREATOR = new Creator () { @Override public Test createFromParcel(Parcel source) { String str = source.readString(); Test test = new Test(str); return test; } @Override public Test[] newArray(int size) { return new Test[size]; } }; Test() { mJson = new JSONObject(); } Test(String json) { try { mJson = new JSONObject(json); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void setValue(String value) { try { mJson.put("value", value); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String getValue() { try { return mJson.getString("value"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public String toString() { return mJson.toString(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(mJson.toString()); } }