数组通过意图的对象列表

时间:2011-11-13 05:40:44

标签: java android

我知道你可以通过intent传入一个String数组列表,但是如果它是我定义的某个对象的数组列表呢?说一个自行车列表,我该怎么做?

4 个答案:

答案 0 :(得分:20)

您可以使对象实现Parcelable并使用putParcelableArrayListExtra。或者,您可以以某种方式序列化对象并放置序列化对象的字节数组。

答案 1 :(得分:19)

这是一个例子。 MainActivity OtherActivity通过Intentclass Person implements Serializable { int id; String name; Person(int i, String s) { id = i; name = s; } } public class TestAndroidActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ArrayList<Person> list = new ArrayList<Person>(); list.add(new Person(1, "Tom")); list.add(new Person(5, "John")); Intent intent = new Intent(this, OtherActitity.class); intent.putExtra("list", list); startActivity(intent); 发送人员列表。

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

public class OtherActitity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.other);

        Intent i = getIntent();
        ArrayList<Person> list = (ArrayList<Person>) i
                .getSerializableExtra("list");
        Toast.makeText(this, list.get(1).name, Toast.LENGTH_LONG).show();

    }
}

OtherActivity.java

{{1}}

答案 2 :(得分:8)

还有一种方法 - 您可以将对象列表序列化为某种字符串表示形式(让它为JSON),然后将字符串值检索回列表

// here we use GSON to serialize mMyObjectList and pass it throught intent to second Activity
String listSerializedToJson = new Gson().toJson(mMyObjectList);
intent.putExtra("LIST_OF_OBJECTS", listSerializedToJson);
startActivity(intent);

// in second Activity we get intent and retrieve the string value (listSerializedToJson) back to list 
String listSerializedToJson = getIntent().getExtras().getString("LIST_OF_OBJECTS");
mMyObjectList = new Gson().fromJson(objectsInJson, MyObject[].class); // in this example we have array but you can easy convert it to list - new ArrayList<MyObject>(Arrays.asList(mMyObjectList)); 

答案 3 :(得分:4)

更好的想法是为你想要放在Intent中的arraylist的对象实现Parcelable接口。例如:

公共类Person实现了Parcelable {

private int id;
private String name;
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
@Override
public int describeContents() {
    return this.hashCode();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeInt(id);
    dest.writeString(name);
}

}

然后你可以说应用程序代码:

bundle.putParcelableArrayList(“personList”,personList);