I’m using Array Adapter to display Array list in List View. I can Add and delete items. Suppose If there is no item in List view, If I select delete its showing Index out of Bind Exception. What I required is it should show toast like “There is no item to delete”.Clarify me Experts!! And my code is below:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bAdd = (Button) findViewById(R.id.button1);
bDel = (Button) findViewById(R.id.button2);
et1 = (EditText) findViewById(R.id.editText1);
et2 = (EditText) findViewById(R.id.EditText2);
et3 = (EditText) findViewById(R.id.EditText3);
lv = (ListView) findViewById(R.id.listView1);
al = new ArrayList<String>();
aa = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_list_item_1, al);
lv.setAdapter(aa);
bAdd.setOnClickListener(new android.view.View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
String str1 = et1.getText().toString();
if (str1.equals("")) {
Toast.makeText(getApplicationContext(),
"Please Enter Item first!!", 0).show();
} else {
al.add(0, str1);
aa.notifyDataSetChanged();
et1.setText("");
}
}
});
bDel.setOnClickListener(new android.view.View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (arg0 == null) {
Toast.makeText(getApplicationContext(),
"Nothing to delete", 0).show();
} else {
al.remove(0);
aa.notifyDataSetChanged();
}
}
});
Just check the size of
allist before you delete it: