通过Intent发送Arraylist [英] send Arraylist by Intent

查看:62
本文介绍了通过Intent发送Arraylist的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过Intent从另一个活动中接收自定义的ArrayList?例如,我在活动A中有这个ArrayList:

How can I receive a custom ArrayList from another Activity via Intent? For example, I have this ArrayList in Activity A:

ArrayList<Song> songs;

如何在活动B中获取此列表?

How could I get this list inside Activity B?

推荐答案

要理解的第一部分是,您使用Intent对象将信息从活动A传递到活动B,您可以在其中放入附加".您可以在Intent中放入的内容的完整列表在此处: https://developer.android.com/reference/android/content/Intent.html (请参见各种putExtra()方法以及下面的putFooExtra()方法).

The first part to understand is that you pass information from Activity A to Activity B using an Intent object, inside which you can put "extras". The complete listing of what you can put inside an Intent is available here: https://developer.android.com/reference/android/content/Intent.html (see the various putExtra() methods, as well as the putFooExtra() methods below).

由于要通过ArrayList<Song>,因此有两个选择.

Since you are trying to pass an ArrayList<Song>, you have two options.

第一个也是最好的方法是使用putParcelableArrayListExtra().要使用此功能,Song类必须实现Parcelable接口.如果您控制Song的源代码,则实现Parcelable相对容易.您的代码可能如下所示:

The first, and the best, is to use putParcelableArrayListExtra(). To use this, the Song class must implement the Parcelable interface. If you control the source code of Song, implementing Parcelable is relatively easy. Your code might look like this:

Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putParcelableArrayListExtra("songs", songs);

第二种方法是使用接受Serializable对象的putExtra()版本.仅在不控制Song的源代码,因此无法实现Parcelable时,才应使用此选项.您的代码可能如下所示:

The second is to use the version of putExtra() that accepts a Serializable object. You should only use this option when you do not control the source code of Song, and therefore cannot implement Parcelable. Your code might look like this:

Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putSerializableExtra("songs", songs);

这就是您将数据放入活动A中的Intent中的方式.如何从活动B中的Intent中获取数据?

So that's how you put the data into the Intent in Activity A. How do you get the data out of the Intent in Activity B?

这取决于您在上面选择的选项.如果选择第一个,则将编写如下内容:

It depends on which option you selected above. If you chose the first, you will write something that looks like this:

List<Song> mySongs = getIntent().getParcelableArrayListExtra("songs");

如果选择第二个,您将编写如下内容:

If you chose the second, you will write something that looks like this:

List<Song> mySongs = (List<Song>) getIntent().getSerializableExtra("songs");

第一种技术的优点在于,它速度更快(就应用程序对用户的性能而言),并且占用的空间更少(就您传递的数据大小而言).

The advantage of the first technique is that it is faster (in terms of your app's performance for the user) and it takes up less space (in terms of the size of the data you're passing around).

这篇关于通过Intent发送Arraylist的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆