检查AsyncTask参数是否为null



我有一个异步任务,用于启动时执行的活动。如果用户手动选择一个位置,则该url包含一个作为参数传递给异步任务的值,如果用户没有指定位置,则异步任务将使用默认url。我的问题是,如果没有指定参数,我就无法对代码调用url[0]。有没有一种方法可以检查并查看参数是否被传递到异步任务中?下面是我的尝试。我试过url[0].isEmpty()url[0] == null,但都给了我IndexOutOfBounds错误。

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);
}

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

您可以通过以下方式检查是否提供了参数:

if(url == null)

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

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

  1. 检查url是否为空:

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

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

最新更新