Intent.putExtra List [duplicate]
Possible Duplicate:
How to put a List in intent
I want to pass a List from one activity to another. So far I have not been successful. This is my code.
//desserts.java
private List<Item> data;
@Override
public void onCreate(Bundle icicle) {
//Code
data.add(new Item(10, "dessert1"));
data.add(new Item(11, "dessert2"));
data.add(new Item(12, "dessert3"));
data.add(new Item(13, "dessert4"));
data.add(new Item(14, "dessert5"));
data.add(new Item(15, "dessert6"));
data.add开发者_如何学Go(new Item(16, "dessert7"));
data.add(new Item(17, "dessert8"));
data.add(new Item(18, "dessert9"));
data.add(new Item(19, "dessert10"));
data.add(new Item(20, "dessert11"));
//Some more code
}
@Override
public void onClick(View v) {
Intent view_order_intent = new Intent(this, thirdpage.class);
view_order_intent.putExtra("data", data);
startActivity(view_order_intent);
}
But I am not able to put data this way. I asked this question earlier but not much happened.
Kindly help. Also help me how to get data in next activity.Assuming that your List is a list of strings make data an ArrayList<String>
and use intent.putStringArrayListExtra("data", data)
Here is a skeleton of the code you need:
Declare List
private List<String> test;
Init List at appropriate place
test = new ArrayList<String>();
and add data as appropriate to
test
.Pass to intent as follows:
Intent intent = getIntent(); intent.putStringArrayListExtra("test", (ArrayList<String>) test);
Retrieve data as follows:
ArrayList<String> test = getIntent().getStringArrayListExtra("test");
If you use ArrayList instead of list then also your problem wil be solved. In your code only modify List into ArrayList.
private List<Item> data;
you can do it in two ways using
Serializable
Parcelable.
This examle will show you how to implement it with serializable
class Customer implements Serializable
{
// properties, getter setters & constructor
}
// This is your custom object
Customer customer = new Customer(name, address, zip);
Intent intent = new Intent();
intent.setClass(SourceActivity.this, TargetActivity.this);
intent.putExtra("customer", customer);
startActivity(intent);
// Now in your TargetActivity
Bundle extras = getIntent().getExtras();
if (extras != null)
{
Customer customer = (Customer)extras.getSerializable("customer");
// do something with the customer
}
Now have a look at this. This link will give you a brief overview of how to implement it with Parcelable.
Look at this.. This discussion will let you know which is much better way to implement it.
Thanks.
//To send from the activity that is calling another activity via myIntent
myIntent.putExtra("id","10");
startActivity(myIntent);
//To receive from another Activity
Bundle bundle = getIntent().getExtras();
String id=bundle.getString("id");
精彩评论