2016-01-21 50 views
0

我創建了一個擴展Application的類,該類存儲具有多個值的ArrayList。 該類用於在整個應用程序中存儲值,以便在需要時訪問它們。如何從自定義適配器類訪問ArrayList,當ArrayList存儲在擴展應用程序的類中時

但是,我不能稱之爲「getApplicationContext()」在我的自定義適配器類,因爲我得到以下錯誤:

error: cannot find symbol method 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(); 
    } 
} 
+3

使列表成爲'static'。但是,如果Application類中的數據可以放在其他地方,那麼它的數據形式就不是很好。 – TheSunny

+0

http://developer.android.com/reference/android/content/Context.html#getApplicationContext()。上下文是您的適配器使用的參數 – Raghunandan

回答

0

而不是使用getApplicationContext()你應該使用getContext().getApplicationContext(),因爲你使用它的ArrayAdapter裏面的。

Context docsArrayAdapter docs

+0

這已解決問題,錯誤不再彈出。謝謝。 –

相關問題