【问题标题】:Making a Global List variable to access from any activity制作一个全局列表变量以从任何活动访问
【发布时间】:2020-02-13 17:04:51
【问题描述】:

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

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

【问题讨论】:

  • 看看ArrayList
  • 如果您想开发购物车应用程序,我认为您需要的知识比您现在所知道的要多。根据您的问题,您可以在这里阅读stackoverflow.com/questions/21724447/…
  • 感谢您的回复。我会审核您的建议

标签: android arraylist global-variables


【解决方案1】:

我按照您的建议解决了。首先是应用类

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

谢谢!

【讨论】:

  • 您是否考虑过使用for each 代替for 循环?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多