2015-11-20 63 views
0

我有一个在启动时执行的活动的异步任务。如果用户手动选择一个位置,那么url包含一个作为asynctask参数传入的值,并且如果用户不指定位置,则异步任务将使用默认url。我的问题是,如果未指定参数,我不能在我的代码上调用url[0]。有没有办法检查并查看参数是否传递到异步任务?以下是我的尝试。我试过url[0].isEmpty()url[0] == null但都给我IndexOutOfBounds错误。检查AsyncTask参数是否为空

private class CallDestination extends AsyncTask<String, Void, JSONObject>{ 
     protected JSONObject doInBackground(String...url){ 

      String MYURL = ""; 

      if(url[0].isEmpty()){ 
       MYURL = "http://thevisitapp.com/api/destinations/read?identifiers=10011"; 
      } else{ 
       MYURL = "http://thevisitapp.com/api/destinations/read?identifiers=" + url[0]; 
      } 
      //TODO make this dynamic as it's passed in from other activity through intent 


      HttpRequest request = new HttpRequest(); 
      return request.getJSONFromUrl(MYURL); 
} 

回答

1

尝试if(url.length ==0)检查它是否为空!

1

如果有一个参数被提供或不提供这样你可以检查:

if(url == null) 

在检查时,得到ArrayIndexOutOfBoundsException异常if(url[0].length == 0)因为urlnull,这基本上意味着数组包含0元素,也意味着您无法访问url[0],因为它会被视为超出范围

0

您知道吗String...String... url是一个数组?因此,可以实现检查的几个层次:

  1. 检查url为空:

    if(url.length() == 0){ 
        //error, no URL given 
    } 
    
  2. 检查url具有价值,但空:

    if(url[0] == null){ 
        //error, url is null 
    }