2014-10-01 49 views
-1

我創建了一個列表如下:如何檢查該列表是否爲空?

Geocoder gc = new Geocoder(this); 
List<Address> list = gc.getFromLocationName(location, 1); 
Address add = list.get(0); 

if (add== null) 
{ 
    Toast.makeText(this,"address not found", Toast.LENGTH_SHORT).show(); 
    return; 
} 

getFromLocationName返回地址列表的功能。 如果找不到地址,則會引發(Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0)

我做了檢查,但它不工作,我的應用程序只是停止...

任何想法,爲什麼?

+0

怎麼樣list.isEmpty()? – mosaad 2014-10-01 10:00:03

+0

list.isEmpty();檢查它 – 2014-10-01 10:01:41

+0

好吧,我檢查它... – 2014-10-01 10:02:46

回答

0
list != null && list.isEmpty() 

在你的情況,如果你要執行的東西只有在列表中包含的數據,然後使用!list.isEmpty()

 Geocoder gc = new Geocoder(this); 
     List<Address> list = gc.getFromLocationName(location, 1); 
     if(list != null && !list.isEmpty()) { 
      Address add = list.get(0); 
      if (add== null) 
       { 
       Toast.makeText(this,"address not found", Toast.LENGTH_SHORT).show(); 
       return; 
       } 
     } 
3
List<Address> list = gc.getFromLocationName(location, 1); 
if(list==null || list.isEmpty()) 
    return; //list is empty 
Address add = list.get(0); 
+0

IMO的正確方法。 – Hristo 2014-10-01 10:04:20

0

試試這個檢查

if(list.length() != 0) 
0

嘗試此

List<Address> list = gc.getFromLocationName(location, 1); 
    if (!list.isEmpty()) { 
     Address add = list.get(0); 
     if (add == null) { 
      Toast.makeText(this, "address not found", Toast.LENGTH_SHORT) 
        .show(); 
      return; 
     } 
    } 
1
if (list.isEmpty()) 
     { 

      Log.i("List is Empty", "Empty List"); 

     } 

//如果列表不爲空或使用清單!= NULL & & list.isEmpty()