【问题标题】:How to access ArrayList from custom adapter class, when the ArrayList is stored in a class that extends Application当 ArrayList 存储在扩展 Application 的类中时,如何从自定义适配器类访问 ArrayList
【发布时间】:2016-01-21 18:40:32
【问题描述】:

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

但是,我无法在我的自定义适配器类中调用“getApplicationContext()”,因为我收到以下错误:

错误:找不到符号方法getApplicationContext()

如果我是正确的,那是因为自定义适配器类没有扩展 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();
    }
}

【问题讨论】:

标签: java android listview arraylist custom-adapter


【解决方案1】:

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

Context docsArrayAdapter docs

【讨论】:

  • 这已经解决了问题,不再弹出错误。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-26
  • 2017-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-04
  • 1970-01-01
相关资源
最近更新 更多