簡體   English   中英

當ArrayList存儲在擴展Application的類中時,如何從自定義適配器類訪問ArrayList

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

我創建了一個擴展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();
    }
}

假設您在ArrayAdapter使用它,而不是使用getApplicationContext() ,應該使用getContext().getApplicationContext()

上下文文檔ArrayAdapter文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM