Intent Putextra Arraylist<Namevaluepair>

Intent putExtra ArrayListNameValuePair

As others have noted, when you want to pass an array as an intent extra, the elements need to implement Serializable. In your case, the approach is fairly simple (not quite — see below): define your own subclass of BasicNameValuePair and declare it to implement the interface.

public class NVP extends BasicNameValuePair implements Serializable {
public NVP(String name, String value) {
super(name, value);
}
}

Then you can use it like you've been trying:

ArrayList<NVP> nameValuePairs = new ArrayList<NVP>();
nameValuePairs.add(new NVP("first_name", first_name));
nameValuePairs.add(new NVP("last_name", last_name));
nameValuePairs.add(new NVP("email", email));
nameValuePairs.add(new NVP("password", password));

/* Move on to step 2 */
Intent intent = new Intent(RegisterActivity1.this, RegisterActivity2.class);
intent.putExtra("nvp", nameValuePairs);
startActivity(intent);

On the receiving end, you'll need to pull it out with:

ArrayList<NVP> nameValuePairs = (ArrayList<NVP>) intent.getSerializable("nvp");

EDIT Well, the above won't work because BasicNameValuePair doesn't have a default constructor and the serialization mechanism requires non-serializable ancestor classes to have a default constructor. Otherwise you'll get an exception on deserialization.

Unfortunately, this means that the solution isn't as simple as I made out. One work-around is to define your own class to implement Parcelable, as @keerthana murugesan suggests in his answer. If you've implemented Parcelable before, you know it's a bit of a pain. Another work-around is to define a class that wraps a BasicNameValuePair (instead of deriving from it) and manages its own serialization:

public class NVP implements NameValuePair, Serializable {
private BasicNameValuePair nvp;

public NVP(String name, String value) {
nvp = new BasicNameValuePair(name, value);
}

@Override
public String getName() {
return nvp.getName();
}

@Override
public String getValue() {
return nvp.getValue();
}

// serialization support

private static final long serialVersionUID = 1L;

private void writeObject(ObjectOutputStream out) throws IOException {
out.writeString(nvp.getName());
out.writeString(nvp.getValue());
}

private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
nvp = new BasicNameValuePair(in.readString(), in.readString());
}

private void readObjectNoData() throws ObjectStreamException {
// nothing to do
}
}

Passing an array of GeoCodes from 1 intent to another

Use serializable while passing data through putExtra()

First Activity:

ArrayList<String> waypoints= new ArrayList<String>();
saveRouteIntent.putExtra("waypoints", waypoints);

In the other Activity:

ArrayList<String> myList = (ArrayList<String>) getIntent().getSerializableExtra("waypoints");


Related Topics



Leave a reply



Submit