我有一个异步任务,用于启动时执行的活动。如果用户手动选择一个位置,则该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,因为url
是null
,这基本上意味着数组包含0个元素,这也意味着您无法访问url[0]
,因为它会被视为超出范围。
您知道String... url
中的String...
是一个数组吗?因此,您可以实现几个级别的检查:
-
检查
url
是否为空:if(url.length() == 0){ //error, no URL given }
-
检查
url
是否有值,但为空:if(url[0] == null){ //error, url is null }