2012-10-19 50 views
1

我使用數組適配器來顯示列表視圖中的數組列表。我可以添加刪除項目。假設如果在列表視圖中沒有項目,如果我選擇刪除其顯示索引超出了綁定異常。我需要的是它應該顯示祝酒像「沒有項目刪除」。澄清我的專家!我的代碼如下:Android:索引超出ArrayList的例外

@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(); 
      } 
     } 
    }); 
+0

請出示您的logcat的 – ashutosh

回答

4

只是檢查al列表的大小,你刪除它之前:在陣列

 if (arg0 == null || al.isEmpty()) { 
      Toast.makeText(getApplicationContext(), 
        "Nothing to delete", 0).show(); 
     } else { 
      al.remove(0); 
      aa.notifyDataSetChanged(); 
     } 
+2

如果列表中沒有任何內容,而不是顯示「Toast」,我也可以建議禁用Delete按鈕。當列表爲空時,屏幕上有一個可用的刪除按鈕會讓人有些困惑。 – acj

+1

使用a1.isEmpty()代替a1.size()== 0 – Stefan

+0

好點。編輯 – Geobits

1

集驗證,見下面

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 { 
      if(al.size == 0){ 
      Toast.makeText(getApplicationContext(), 
        "There is no item to delete", 0).show(); 
       return; 
      } 
      al.remove(0); 
      aa.notifyDataSetChanged(); 
     } 
    } 
});