问题描述:

I have a complex object (which includes further objects and hashmaps). All objects implement Serializable.

In the first activity I do:

public void secondActivity(MyObject o) {

Intent intent = new Intent(this, SecondActivity.class);

intent.putExtra("myobject", o);

startActivity(intent);

finish();

}

Then, in the second activity I'm doing:

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

Intent intent = getIntent();

MyObject o = (MyObject)intent.getSerializableExtra("myobject");

}

But when casting I'm getting this exception:

java.lang.ClassCastException: java.util.ArrayList cannot be cast to myapp.MyObject

Is this the correct way to pass complex objects between activities? What am I missing?

Or should I implement singleton class?

网友答案:

You are doing all fine, so I think that can be:

  • your are sending to secondActivity method an incorrect object (like ArrayList instead of correct MyObject)
  • Please look if you are using this key "myobject" in other part of the code and setting other object in putExtra.

  • verify MyObject class and look if some variable is an ArrayList and remove it (just to test)

  • your custom object not have "implements Serializable" like:

    public class MyObject implements Serializable {

    //variables and methods

    }

So, I suggest that you verify this, and I think is better use Singleton class or Parcelable instead of Serializable, because Google says that is better acording to Good Practice. Please look this answer stackoverflow

I make some app and implement serializable, my custom object is:

public class Stores implements Serializable {
private static final long serialVersionUID = 1L;
public Integer id;
public String name;
public String store_hours;
public String telephone;
public String fax;
public String latitude;
public String longitude;

}

My firt Activity:

private void showDialog(Stores store)
    {
        Intent intent = new Intent(this,DisplayDialogActivity.class);
        intent.putExtra("Locations",store);
        startActivityForResult(intent, 0);
    }

And my second activity

Stores store = (Stores) getIntent().getSerializableExtra("Locations");

PD: I don't know speak english very well, so apologize for this.

相关阅读:
Top