简体   繁体   English

无法将ArrayList发送到其他非活动类:

[英]Can't send ArrayList to other non-activity class:

Here i am declaring the arraylist and adding value to it: 在这里,我宣布arraylist并为其增加价值:

private ArrayList<String> act = new ArrayList<String>();
act.add("ds");

Here i am creating the method which is returning the arraylist: 在这里,我正在创建返回arraylist的方法:

public ArrayList<String> getAct() {
        return act;
}

Here i am getting it: 我在这里得到它:

private ArrayList<String> act = new MainActivity().getAct();

And when i get the size of act is 0(it is empty). 当我得到act的大小是0(它是空的)。 Can you tell me why? 你能告诉我为什么吗?

If you're using construction new MainActivity().getAct() you have to fill your array in Activity constructor. 如果你正在使用构造new MainActivity().getAct()你必须在Activity构造函数中填充你的数组。 So if you're doing it in lifecycle, it will will be empty. 因此,如果你在生命周期中这样做,它将是空的。

It's better to use static factory to provide your array and pass it later to your activity. 最好使用静态工厂来提供数组并稍后将其传递给您的活动。

When you create a new instance of any class, all non-static variables are initialized to their default values. 当您创建任何类的new实例时,所有非静态变量都将初始化为其默认值。 If you really want to get the ArrayList in that way, either you need to use the same Activity reference: 如果您真的想以这种方式获取ArrayList ,则需要使用相同的Activity引用:

private ArrayList<String> act = mainActivity.getAct();

or you need to make that variable static : 或者您需要将该变量设为static

private static ArrayList<String> act = new ArrayList<String>();

Then the following will work: 然后以下将工作:

private ArrayList<String> act = new MainActivity().getAct();

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

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