How to pass ArrayList<Coordinate[]> from one Activity to another
I have tried all day to do this and haven't had any luck. I have an ArrayList with an Array of Coordinate types inside, and I want to pass this from one activity to another. I don't think this is possible through using Intent. So I am wondering what开发者_开发百科 other option do I have? I want something simple..
I'd probably put the values in a database in your first activity and only pass some unique identifier on to the second activity so it can recreate the ArrayList on the other side. But if you want a quick solution, use the intent bundle and serialize/deserialize the coordinates yourself:
ArrayList<Coordinate> mCoords = new ArrayList<Coordinate>();
private void startOtherActivity()
{
int numCoords = mCoords.size();
Intent intent = new Intent();
intent.putExtra("coord_size", numCoords);
for (int i = 0; i < numCoords; i++)
{
Coordinate coord = mCoords.get(i);
intent.putExtra("coord_x_" + i, coord.getX());
intent.putExtra("coord_y_" + i, coord.getY());
}
//start other activity...
}
Then grab the values out of the bundle on the other side and regen the ArrayList.
Edit: Just realized you're talking about Coordinate[]s. Same principle still applies, just nest another for loop in there and keep track of each individual array's length as well.
Update: On the other side, you'd have something like
int len = intent.getIntegerExtra("coord_size", 0);
for(int i = 0; i < len; i++)
{
float x = intent.getFloatExtra("coord_x_" + i, 0.0);
float y = intent.getFloatExtra("coord_y_" + i, 0.0);
mCoords.add(new Coordinate(x, y));
}
You can have a singleton "Model" class, on which you can store the ArrayList object from one activity, and retrieve it from another.
Create Bundle and try to put the ArrayList. Then send the bundle in the intent.
You could write a ParcelableCoordinate class that implements Parcelable, and then have it convert the Coordinate objects into ParcelableCoordinate objects, put them in the intent, and then do the reverse on the other side.
精彩评论