简体   繁体   English

如何在不同的活动(Android和Java)中使用相同的ArrayList

[英]How to use the same ArrayList in different activities (Android and Java)

I am working on a little app and needed a way of making it so when a button is pushed it opens up a random activity, and then doesn't open up that activity again. 我正在开发一个小应用程序,需要一种制作方法,因此当按下按钮时,它会打开一个随机活动,然后不再打开该活动。

I did this by making an ArrayList which is randomly sorted and has a number chosen from it. 我是通过创建一个ArrayList进行随机排序的,并从中选择了一个数字。 This number is then deleted. 然后删除该号码。 The number chosen is then used to open up one of the activities. 然后,使用所选的数字来打开活动之一。

However, when I get to another activity I cannot use the same ArrayList from before (with all the same numbers in). 但是,当我进行另一项活动时,无法使用之前的相同ArrayList(所有相同的数字)。

Is there a way to move the ArrayList from activity to activity? 有没有办法将ArrayList从活动移动到活动?

Thanks in advance! 提前致谢!

Here is my code for making the ArrayList and picking a number: 这是我制作ArrayList并选择一个数字的代码:

                int min = 1;
                int max = 3;
                ArrayList<Integer> list = new ArrayList<Integer>();
                for(int i = min; i <= max; i++) list.add(i);
                Collections.shuffle(list);

                Integer x = list.get(0);
                list.remove(0); 

You can pass it in your startActivity intent (intent.putExtra) or you can use a static variable in your application class: 您可以在startActivity意向(intent.putExtra)中传递它,也可以在应用程序类中使用静态变量:

How to declare global variables in Android? 如何在Android中声明全局变量?

For passing an ArrayList with an intent, this is a very useful post: 对于有意图地传递ArrayList,这是一个非常有用的文章:

Pass arraylist of user defined objects to Intent android 将用户定义对象的arraylist传递给Intent android

Basically, if you use all primitives you can pass them without creating parcelable objects to put into it. 基本上,如果使用所有基元,则可以传递它们而无需创建可打包对象。 You also do not have to create a parcelable object (because objects that do not extend or implement parcelable cannot successfully be passed in an intent even though you will not see any errors). 您也不必创建可拆分的对象(因为不会扩展或实现可拆分的对象无法成功地通过意图传递,即使您不会看到任何错误)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM