Reputation: 197
I need add data to gridview table, when button is click. My code:
String[] data = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"};
GridView gvMain;
ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.smena);
adapter = new ArrayAdapter<String>(this, R.layout.item, R.id.tvText, data);
gvMain = (GridView) findViewById(R.id.gridView1);
gvMain.setAdapter(adapter);
Button but1=(Button) findViewById(R.id.button1);
but1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
ButtonOn (1);
}
});
}
public void ButtonOn (int Art){
adapter.add("1");
gvMain.setAdapter(adapter);
}
When I Click button, my application has stoped unexpectedly.
Upvotes: 0
Views: 2099
Reputation: 1584
What kind of error is the LogCat showing...
If its showing you a 'null pointer exception' or 'Unable to start activity' then you should try inflating all the items in a single activity or else intent the data properly to your activity and display the GridView in a new activity.
hope you understand my idea. And more importantly it is not suggested to use Activities as contents of Activity because they consume more memory. I know there are many tutorials which follow the same but hide the drawback.
Upvotes: 0
Reputation: 12717
ArrayAdapter converts the array into a AbstractList (List) which cannot be modified. Use an ArrayList instead using an array while initializing the ArrayAdapter.
String[] data = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k" };
ArrayList<String> lst = new ArrayList<String>();
GridView gvMain;
ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.smena);
lst.addAll(Arrays.asList(data));
adapter = new ArrayAdapter<String>(this, R.layout.title_bar, R.id.editText1,lst);
gvMain = (GridView) findViewById(R.id.gridView1);
gvMain.setAdapter(adapter);
Button but1 = (Button) findViewById(R.id.button1);
but1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
ButtonOn(1);
}
});
}
public void ButtonOn(int Art) {
lst.add("1");
gvMain.setAdapter(adapter);
}
Upvotes: 1
Reputation: 1271
Try This Code
String[] items = {"a","b","c","d","e","f"};
Button b = (Button)findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
GridView gridView = (GridView)findViewById(R.id.gridView1);
gridView.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, items));
(or)
gridView.setAdapter(new ArrayAdapter<String>(getApplicationContext(),R.layout.cust, R.id.textView1, items));
}
});
Upvotes: 0