通过Intent传递ArrayList

85

我正在尝试使用意图将一个ArrayList传递到另一个活动中。以下是第一个活动中的代码。

case R.id.editButton:
        Toast.makeText(this, "edit was clicked", Toast.LENGTH_LONG).show();
        Intent intent = new Intent(this, editList.class);
        intent.putStringArrayListExtra("stock_list", stock_list);
        startActivity(intent);
        break;

这是我试图在第二个活动中检索列表的位置。这里有什么问题吗?

Intent i = new Intent(); //This should be getIntent();
    stock_list = new ArrayList<String>();

    stock_list = i.getStringArrayListExtra("stock_list");
6个回答

109

在你的接收意图中,你需要做:

Intent i = getIntent();  
stock_list = i.getStringArrayListExtra("stock_list");
你当前的做法只是创建了一个没有任何额外参数的新意图。
如果你只有一个额外参数,可以将代码简化为:
stock_list = getIntent().getStringArrayListExtra("stock_list");

24

我已经通过以字符串形式传递ArrayList来完成这个。

  1. build.gradledependencies块中添加compile 'com.google.code.gson:gson:2.2.4'

  2. 点击Sync Project with Gradle Files

Cars.java:

public class Cars {
    public String id, name;
}

FirstActivity.java

当您想要传递ArrayList时:

List<Cars> cars= new ArrayList<Cars>();
cars.add(getCarModel("1", "A"));
cars.add(getCarModel("2", "B"));
cars.add(getCarModel("3", "C"));
cars.add(getCarModel("4", "D"));

Gson gson = new Gson();

String jsonCars = gson.toJson(cars);

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("list_as_string", jsonCars);
startActivity(intent);

按照功能获取CarsModel

private Cars getCarModel(String id, String name){
       Cars cars = new Cars();
       cars.id = id;
       cars.name = name;
    return cars;
 }

SecondActivity.java

onCreate()方法中,你需要导入java.lang.reflect.Type类来检索ArrayList

String carListAsString = getIntent().getStringExtra("list_as_string");

Gson gson = new Gson();
Type type = new TypeToken<List<Cars>>(){}.getType();
List<Cars> carsList = gson.fromJson(carListAsString, type);
for (Cars cars : carsList){
   Log.i("Car Data", cars.id+"-"+cars.name);
}

希望这能节省时间,我已经保存了它。

完成


3
您可以让您的汽车模型类实现Parcelable接口,然后简单地执行intent.putParcelableArrayListExtra("parecelable_list", carsList)。这里的carsList是ArrayList<Cars>的一个实例。 - Nouman Hanif
2
Downvoter 应该注意添加评论作为原因。 - Hiren Patel
3
如果已经有intent.putStringArrayListExtraintent.getStringArrayListExtragetSerializableExtra存在,为什么要使用Gson?如果我使用的是Eclipse,该怎么办?我需要下载并添加Gson库吗? - Tushar Monirul
我的看法是...你不能因为这个原因而对此进行反对,但是应该推荐使用Parceling而不是Serialization,因为已经被证明了很多次 - 对于Android来说,Parceling更有效率且性能超越Serialization。 - user3833732

13

如果你使用通用数组列表类(Class)而不是特定类型,那么:

示例:

private ArrayList<Model> aListModel = new ArrayList<Model>();

在这里,Model = Class

接收 Intent 如下:

aListModel = (ArrayList<Model>) getIntent().getSerializableExtra(KEY);

必须记住:

这里的Model-class必须实现如下所示: ModelClass implements Serializable


通常像startActivityForResult一样发送Intent:Intent intent = new Intent(MainActivity.this, SecondActivity.class); startActivityForResult(intent, aListModel); - Dhruv Raval

5
假设您需要将以下类的arraylist从当前活动传递到下一个活动 //对象的类在arraylist中 //请记得从Serializable接口实现类 //Serializable意味着它将对象转换为字节流,并帮助传输该对象
public class Question implements Serializable {
... 
... 
...
}

在您当前的活动中,您可能有一个如下的ArrayList:
ArrayList<Question> qsList = new ArrayList<>();
qsList.add(new Question(1));
qsList.add(new Question(2));
qsList.add(new Question(3));

// intialize Bundle instance
Bundle b = new Bundle();
// putting questions list into the bundle .. as key value pair.
// so you can retrieve the arrayList with this key
b.putSerializable("questions", (Serializable) qsList);
Intent i = new Intent(CurrentActivity.this, NextActivity.class);
i.putExtras(b);
startActivity(i);

为了在下一个活动中获取ArrayList,请按照以下步骤操作:
//get the bundle
Bundle b = getIntent().getExtras();
//getting the arraylist from the key
ArrayList<Question> q = (ArrayList<Question>) b.getSerializable("questions");

3
//arraylist/Pojo you can Pass using bundle  like this 
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
Bundle args = new Bundle();
                        args.putSerializable("imageSliders",(Serializable)allStoriesPojo.getImageSliderPojos());
                        intent.putExtra("BUNDLE",args);
 startActivity(intent); 


Get SecondActivity like this
  Intent intent = getIntent();
        Bundle args = intent.getBundleExtra("BUNDLE");
String filter = bundle.getString("imageSliders");

//Happy coding

它抛出了一个异常:java.lang.ClassCastException: com.example.ModelObjectNameHere 无法转换为 java.io.Serializable - Ali Tamoor

2
    public class StructMain implements Serializable {
    public  int id;
    public String name;
    public String lastName;
}

这是我的项目。实现Serializable接口并创建ArrayList。

ArrayList<StructMain> items =new ArrayList<>();

并放入Bundle中
Bundle bundle=new Bundle();
bundle.putSerializable("test",items);

创建一个新的Intent,并将Bundle放入Intent中

Intent intent=new Intent(ActivityOne.this,ActivityTwo.class);
intent.putExtras(bundle);
startActivity(intent);

如果要接收bundle,请插入以下代码:

Bundle bundle = getIntent().getExtras();
ArrayList<StructMain> item = (ArrayList<StructMain>) bundle.getSerializable("test");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接