How can I access to an ArrayList from another class?

非 Y 不嫁゛ 提交于 2020-01-01 22:32:51

问题


I have an ArrayList of Car:

ArrayList<Car> cars = new ArrayList<Car>();

that I fill on my onCreate method of my MainActivity.java with an AsyncTask:

new fillCars().execute();

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.

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:

In MainActivity.java

public MainActivity(){

}

//Here the method onCreate 

public ArrayList<Car> getCars(){
    return cars;
}

In ModifyCars.java

MainActivity MA = new MainActivity();
Log.d("prove",Integer.toString(MA.getCars().size())); //Here the size it's 0

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.

Thanks in advance!


回答1:


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,

In MainActivity :

static ArrayList<Car> cars = new ArrayList<Car>();
and in your ModifyCars.java access it as,

    ArrayList<Car> myCars = MainActivity.cars

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);

and in ModifyCars activity you should extract it from intent as,

Intent i = getIntent();
ArrayList<Car> myCars = (ArrayList<Car>) i.getSerializableExtra("CAR_ARRAY_LIST");


来源:https://stackoverflow.com/questions/32267826/how-can-i-access-to-an-arraylist-from-another-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!