I have a problem with my shoping list application. I implemented a button adapter from this tutorial which I will use for adding products to list. Each buuton in my gridview will be a product and each product will have context menu where I can add it to list or delete the product.
Problem is that user should have ability to add new products or categories and I don't know how to add items to gridview at runtime. I thought that I could create some dynamic array like list in c++ but i'm new to android and java so I have no idea how to implement something like that.
I tried to implement stack but every time I try to push something app crashes. The same is with array list.
ButtonAdapter :
ButtonAdapter(Context c, ArrayList<String> array){
mContext = c;
arrayInAdapter = array; }
public int getCount() {
int a;
a = arrayInAdapter.size();
return a;
}
public View getView(int position, View convertView, ViewGroup parent) {
Button btn;
if (convertView == null) {
//if it's not recycled, initialize some attributes
btn = new Button(mContext);
btn.setLayoutParams(new GridView.LayoutParams(130, 130));
btn.setPadding(8, 8, 8, 8);
}
else {
btn = (Button) convertView;
}
btn.setText(arrayInAdapter.get(position));
btn.setTextColor(Color.RED);
btn.setBackgroundResource(R.drawable.sample_0);
btn.setId(position);
btn.setOnClickListener(new MyOnClickListener(position));
return btn;
}
}
and in Grid Activity i have another arraylist
public static ArrayList<String> arrayInGrid;
in onCreate:
gridView.setAdapter(new ButtonAdapter(this,arrayInGrid ));
but when i try to send new item to array program crashes.
arrayInGrid.add("new");
In fact it crashes at
arrayInAdapter.size();
in button adapter.
any ideas what is wrong?
You can pass the values in your dynamic array to the BaseAdapter for that GridView. Here's a tutorial, Hope it will help you. http://www.mkyong.com/android/android-gridview-example/