如何从另一个类访问 ArrayList? [英] How can I access to an ArrayList from another class?
问题描述
我有一个Car
的ArrayList
:
ArrayList<Car> cars = new ArrayList<Car>();
我用 AsyncTask 填充我的 MainActivity.java
的 onCreate
方法:
that I fill on my onCreate
method of my MainActivity.java
with an AsyncTask:
new fillCars().execute();
我想要的是在其他名为 ModifyCars.java
的类中使用这个 ArrayList cars
.我的问题是在 AsyncTask
之后它在方法 onCreate
上执行,在所有类 MainActivity.java
ArrayList cars
它已填充,我可以使用其中的数据,但是当我将它传递给 ModifyCars.java
时,它的大小等于 0
.
What I want it's to use this ArrayList cars
in other class, named ModifyCars.java
. My problem it's that after the AsyncTask
it's executed on the method onCreate
, in all the class MainActivity.java
the ArrayList cars
it's fill and I can use the data inside of it but when I pass it to ModifyCars.java
the size it's equals to 0
.
我用来传递这个 ArrayList
的方法是创建一个 MainActivity.java
类的空构造函数并创建一个 get 方法.在 ModifyCars.java
类中,我创建了一个 MainActivity
对象并尝试使用我之前创建的 get 方法.这是我用于此目的的代码:
The method that I use to pass this ArrayList
it's to create an empty constructor of the class MainActivity.java
and create a get method. In the class ModifyCars.java
I create an object of MainActivity
and try to use the get method that I created before. Here the code that I used for this purpose:
在MainActivity.java
public MainActivity(){
}
//Here the method onCreate
public ArrayList<Car> getCars(){
return cars;
}
在ModifyCars.java
MainActivity MA = new MainActivity();
Log.d("prove",Integer.toString(MA.getCars().size())); //Here the size it's 0
如何在我的 ModifyCars.java
类中使用我的 cars
ArrayList(当然,已填充)?我做错了什么?
How can I use my cars
ArrayList (of course, filled) in my ModifyCars.java
class? What am I doing wrong?
我在互联网上搜索,但没有任何对我有用的东西.任何帮助将不胜感激.
I search on the Internet but nothing had been useful for me. Any help would really appreciated.
提前致谢!
推荐答案
您正在创建 MainActivity 的一个新实例,这就是为什么您在那里得到一个空数组列表的原因.一个简单的解决方案是使您的 arryalist 保持静态并按如下方式访问它,
You are creating a new instance of the MainActivity that's why you are getting an empty array list there. A simple solution to that would be making your arryalist static and access it as below,
在主活动中:
static ArrayList<Car> cars = new ArrayList<Car>();
并在您的 ModifyCars.java 中访问它,
and in your ModifyCars.java access it as,
ArrayList<Car> myCars = MainActivity.cars
但是执行此操作的标准方法是,将数组列表发送到 ModifyCars 活动,同时通过如下意图调用它,
But a standard way to do this would be, sending the array list to the ModifyCars activity while calling it through intent as below,
Intent i = new Intent(this, ModifyCars.class);
i.putExtra("CAR_ARRAY_LIST", this.cars);
startActivity(i);
并且在 ModifyCars 活动中,您应该将其从意图中提取为,
and in ModifyCars activity you should extract it from intent as,
Intent i = getIntent();
ArrayList<Car> myCars = (ArrayList<Car>) i.getSerializableExtra("CAR_ARRAY_LIST");
这篇关于如何从另一个类访问 ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!