当 ArrayList 存储在扩展应用程序的 class 中时,如何从自定义适配器 class 访问 ArrayList

How to access ArrayList from custom adapter class, when the ArrayList is stored in a class that extends Application

我创建了一个 class 来扩展应用程序,它存储一个包含多个值的 ArrayList。 class 用于在整个应用程序中存储值,因此我可以在需要时访问它们。

但是,我无法在自定义适配器 class 中调用 'getApplicationContext()',因为出现以下错误:

error: cannot find symbol method getApplicationContext()

如果我是对的,那是因为自定义适配器 class 没有扩展 AppCompatActivity。

有人知道解决这个问题的方法吗?最终,我试图从存储的 ArrayList 创建一个 ListView。

我的代码如下。

public class CartListAdapter extends ArrayAdapter<Product> {
    private ArrayList<Product> products;

    public CartListAdapter(Context context, int textViewResourceId, ArrayList<Product> products ) {
        super(context, textViewResourceId, products);

        this.products=products;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View row = inflater.inflate(R.layout.activity_cart_row_item, parent, false);


        final Global globalVariables = (Global) getApplicationContext();

        //get product stored in array that exists in Application class
        Product p = globalVariables.getMyProducts(position);


        TextView name = (TextView) row.findViewById(R.id.cart_product_name);
        TextView price = (TextView) row.findViewById(R.id.cart_product_price);
        TextView quantity = (TextView) row.findViewById(R.id.cart_quantity_text);
        TextView type = (TextView) row.findViewById(R.id.cart_type);
        TextView option = (TextView) row.findViewById(R.id.cart_option);


        name.setText(p.getProductName());
        price.setText(p.getProductPrice());
        quantity.setText(p.getProductQuantity());
        type.setText(p.getProductType());
        option.setText(p.getProductOption());

        return row;
    }
}

public class Global extends Application {


private ArrayList <Product> myProducts = new ArrayList<>();
    private Cart cart;

    public Cart getCart() {

        return cart;
    }

    public void setCart(Cart cart) {

        this.cart = cart;
    }

    public Product getMyProducts(int position) {
        return myProducts.get(position);
    }

    public void addMyProducts(Product product) {
        myProducts.add(product);
    }

    public int getMyProductsSize (){
        return myProducts.size();
    }
}

您应该使用 getContext().getApplicationContext() 而不是 getApplicationContext(),因为您在 ArrayAdapter 中使用它。

Context docs and ArrayAdapter docs.