首页 > 解决方案 > 制作一个全局列表变量以从任何活动访问

问题描述

我正在开发一个购物车应用程序,需要有产品列表和每个产品库存。为此,我要做的是实现一个全局列表变量。我已经阅读了有关全局变量的信息,并且可以实现它,但无法弄清楚列表的形式。任何关于如何实施它的建议或帮助都会很棒,谢谢。

public class Application extends android.app.Application {

    private int data;

    public int getData(){
        return data;
    }

    public void setData(int d){
        this.data=d;
    }
}

((Application) this.getApplication()).setData(0);
x1=((Application) this.getApplication()).getData();

标签: androidarraylistglobal-variables

解决方案


我按照你的建议弄清楚了。首先在应用类

public class Application extends android.app.Application {


    public ArrayList myGlobalArray = null;

    public Application() {
        myGlobalArray = new ArrayList();
    }
}

然后对于我的应用程序的 porpouse,我在它们各自的索引上添加了各自的值

    for (int i=0;i<productsList.size();i++){
        if (productsList.get(i).idProduct==idProduct){
            values.add(i,Integer.parseInt(txtQuantity.getText().toString()));
            ((Application)getApplicationContext()).myGlobalArray = (ArrayList) values;
        }
    }

当我需要获取值时

    ArrayList<Integer> test = new ArrayList<>();
    for (int d=0;d< ((Application) getApplicationContext()).myGlobalArray.size();d++) {
        test.add((Integer) ((Application)getApplicationContext()).myGlobalArray.get(d));
    }

谢谢!


推荐阅读