我如何通过一个自定义类型的对象从一个活动到另一个使用类意图的putExtra()方法?


当前回答

如果你的对象类实现了Serializable,你不需要做任何其他事情,你可以传递一个Serializable对象。这就是我用的。

其他回答

如果你有一个单例类(fx Service)作为你的模型层的网关,它可以通过在该类中有一个带有getter和setter的变量来解决。

活动一:

Intent intent = new Intent(getApplicationContext(), Activity2.class);
service.setSavedOrder(order);
startActivity(intent);

活动二:

private Service service;
private Order order;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_quality);

    service = Service.getInstance();
    order = service.getSavedOrder();
    service.setSavedOrder(null) //If you don't want to save it for the entire session of the app.
}

在服务:

private static Service instance;

private Service()
{
    //Constructor content
}

public static Service getInstance()
{
    if(instance == null)
    {
        instance = new Service();
    }
    return instance;
}
private Order savedOrder;

public Order getSavedOrder()
{
    return savedOrder;
}

public void setSavedOrder(Order order)
{
    this.savedOrder = order;
}

此解决方案不需要对相关对象进行任何序列化或其他“打包”。但是,只有在使用这种架构时才会有好处。

对于你知道要在应用程序中传递数据的情况,使用“全局变量”(比如静态类)

以下是Dianne Hackborn (hackbod -谷歌安卓软件工程师)对此事的看法:

For situations where you know the activities are running in the same process, you can just share data through globals. For example, you could have a global HashMap<String, WeakReference<MyInterpreterState>> and when you make a new MyInterpreterState come up with a unique name for it and put it in the hash map; to send that state to another activity, simply put the unique name into the hash map and when the second activity is started it can retrieve the MyInterpreterState from the hash map with the name it receives.

你可以使用putExtra(Serializable..)和getSerializableExtra()方法来传递和检索你的类类型的对象;你必须将你的类标记为Serializable,并确保你所有的成员变量也是Serializable…

Start another activity from this activity pass parameters via Bundle Object

Intent intent = new Intent(this, YourActivity.class);
Intent.putExtra(AppConstants.EXTRAS.MODEL, cModel);
startActivity(intent);
Retrieve on another activity (YourActivity)

ContentResultData cModel = getIntent().getParcelableExtra(AppConstants.EXTRAS.MODEL);

你可以使用android BUNDLE来做到这一点。

从你的类中创建一个Bundle,像这样:

public Bundle toBundle() {
    Bundle b = new Bundle();
    b.putString("SomeKey", "SomeValue");

    return b;
}

然后用INTENT传递这个bundle。 现在你可以通过传递bundle来重新创建你的类对象

public CustomClass(Context _context, Bundle b) {
    context = _context;
    classMember = b.getString("SomeKey");
}

在自定义类中声明并使用。