【问题标题】:Check if AsyncTask parameter is null检查 AsyncTask 参数是否为空
【发布时间】:2015-11-20 00:54:47
【问题描述】:

我有一个在启动时执行的活动的异步任务。如果用户手动选择一个位置,该 url 包含一个作为参数传递给 asynctask 的值,并且如果用户没有指定位置,则 async 任务使用默认 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);
}

【问题讨论】:

    标签: android android-asynctask indexoutofboundsexception


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      if(url == null)
      

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

      【讨论】:

        【解决方案3】:

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

        1. 检查url是否为空:

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

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

        【讨论】:

          猜你喜欢
          • 2014-07-04
          • 1970-01-01
          • 1970-01-01
          • 2013-05-01
          • 2011-04-21
          • 1970-01-01
          • 2016-03-28
          • 2018-05-20
          • 1970-01-01
          相关资源
          最近更新 更多