AsyncTask中的方法执行不适用于String

时间:2017-07-18 17:58:21

标签: android android-asynctask

我尝试像这样执行AsyncTask

private static final String REQUESTED_URL = "//my url";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.earthquake_activity);
    EarthQuakeAsyncTask task = new EarthQuakeAsyncTask();
    task.execute(REQUESTED_URL); //this is where the error is
}

但Android Studio表示它无法解析方法execute(String)。我有来自Udacity的教程,他们的样本非常相似

/** URL for earthquake data from the USGS dataset */
private static final String USGS_REQUEST_URL =
        "//url";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    EarthquakeAsyncTask task = new EarthquakeAsyncTask();
    task.execute(USGS_REQUEST_URL); //it works
}

有人可以告诉我为什么会发生这种情况吗?

修改:这是我的EarthQuakeAsyncTask课程:

private class EarthQuakeAsyncTask extends AsyncTask<URL,Void,ArrayList<EarthQuake>> {
    @Override
    protected ArrayList<EarthQuake> doInBackground(URL... urls) {
        if(urls.length==0||urls[0]== null){
            return null;
        }
        // Create URL object
        URL url = createUrl(REQUESTED_URL);
        try {
            jsonResponse = makeHttpRequest(url);
        } catch (IOException e) {
            // TODO Handle the IOException
        }
        ArrayList<EarthQuake> earthquake = QueryUtils.extractEarthquakes(jsonResponse);
        return earthquake;
    }

    @Override
    protected void onPostExecute(ArrayList<EarthQuake> earthquake) {
        if (earthquake == null) {
            return;
        }
        updateUi();
    }


    private URL createUrl(String stringUrl) {
        URL url;
        try {
            url = new URL(stringUrl);
        } catch (MalformedURLException exception) {
            Log.e(LOG_TAG, "Error with creating URL", exception);
            return null;
        }
        return url;
    }

    private String makeHttpRequest(URL url) throws IOException {
        // If the URL is null, then return early.
        if (url == null) {
            return jsonResponse;
        }

        HttpURLConnection urlConnection = null;
        InputStream inputStream = null;
        try {
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(10000 /* milliseconds */);
            urlConnection.setConnectTimeout(15000 /* milliseconds */);
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();
            // If the request was successful (response code 200),
            // then read the input stream and parse the response.
            if (urlConnection.getResponseCode() == 200) {
                inputStream = urlConnection.getInputStream();
                jsonResponse = readFromStream(inputStream);
            } else {
                Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
            }
        } catch (IOException e) {
            Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }
        return jsonResponse;
    }

    private String readFromStream(InputStream inputStream) throws IOException {
        StringBuilder output = new StringBuilder();
        if (inputStream != null) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line = reader.readLine();
            while (line != null) {
                output.append(line);
                line = reader.readLine();
            }
        }
        return output.toString();
    }
}

}

2 个答案:

答案 0 :(得分:0)

这是因为您的AsyncTask类没有以使用String参数处理execute方法的方式定义。让我解释一下自己。

您开发的AsyncTask类将如下所示:

private class MyAsyncTask extends AsyncTask<TYPE1, TYPE2, TYPE3> {

     protected TYPE3 doInBackground(TYPE1... type1_variables) {
         // Do some long process here..
         return variable_of_type_TYPE3;
     }

     protected void onPostExecute(TYPE3 result) {
         // Do something here
     }
 }

因此,要调用task.execute(REQUESTED_URL);,您需要正确实现AsyncTask类。

例如,它可能如下所示:

private class EarthQuakeAsyncTask extends AsyncTask<String, Void, Void> {
     ...
}

答案 1 :(得分:0)

您的类签名表明您希望将URL类型作为参数,但是您在execute()方法中传递String类型。您需要做的就是更改您的类签名,以期望在此代码中使用String。

 private class EarthQuakeAsyncTask extends AsyncTask<String,Void,ArrayList<EarthQuake>> {
        @Override
        protected ArrayList<EarthQuake> doInBackground(String... urls) {
            if(urls.length==0||urls[0]== null){
                return null;
            }
            // Create a URL object from the String passed to the execute method
            URL url = createUrl(urls[0]);
            try {
                jsonResponse = makeHttpRequest(url);
            } catch (IOException e) {
                // TODO Handle the IOException
            }
            ArrayList<EarthQuake> earthquake = QueryUtils.extractEarthquakes(jsonResponse);
            return earthquake;
        }

        @Override
        protected void onPostExecute(ArrayList<EarthQuake> earthquake) {
            if (earthquake == null) {
                return;
            }
            updateUi();
        }


        private URL createUrl(String stringUrl) {
            URL url;
            try {
                url = new URL(stringUrl);
            } catch (MalformedURLException exception) {
                Log.e(LOG_TAG, "Error with creating URL", exception);
                return null;
            }
            return url;
        }

        private String makeHttpRequest(URL url) throws IOException {
            // If the URL is null, then return early.
            if (url == null) {
                return jsonResponse;
            }

            HttpURLConnection urlConnection = null;
            InputStream inputStream = null;
            try {
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setReadTimeout(10000 /* milliseconds */);
                urlConnection.setConnectTimeout(15000 /* milliseconds */);
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();
                // If the request was successful (response code 200),
                // then read the input stream and parse the response.
                if (urlConnection.getResponseCode() == 200) {
                    inputStream = urlConnection.getInputStream();
                    jsonResponse = readFromStream(inputStream);
                } else {
                    Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
                }
            } catch (IOException e) {
                Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            }
            return jsonResponse;
        }

        private String readFromStream(InputStream inputStream) throws IOException {
            StringBuilder output = new StringBuilder();
            if (inputStream != null) {
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
                BufferedReader reader = new BufferedReader(inputStreamReader);
                String line = reader.readLine();
                while (line != null) {
                    output.append(line);
                    line = reader.readLine();
                }
            }
            return output.toString();
        }
    }
    }