我试图了解AsyncTask的工作原理。我有以下代码,但是我收到以下错误:Class' AsyncTask'必须被宣布为抽象的或实现抽象方法' doInBackground(Params ...)'
private class WeatherDataTask extends AsyncTask<Void, Void, String> {
protected String doInBackgrond() throws Exception{
HttpURLConnection connection = null;
BufferedReader reader = null;
String data = null;
try{
URL url = new URL("http://api.openweathermap.org/data/2.5/weather?zip=90210,us&units=imperial");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream stream = connection.getInputStream();
StringBuffer buffer = new StringBuffer();
reader = new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
data = null;
}
return data = buffer.toString();
} catch (IOException e) {
Log.e("PlaceholderFragment", "Error ", e);
data = null;
return data;
} finally{
if (connection != null) {
connection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("PlaceholderFragment", "Error closing stream", e);
}
}
}
}
protected void onPostExecute(String jsonParse){
if(jsonParse == null){
TextView progress = (TextView) findViewById(R.id.container);
progress.setText("Unable to get weather");
}
else {
try {
JSONObject jsonRootObject = new JSONObject(jsonParse);
int temp = Integer.parseInt(jsonRootObject.getJSONObject("main").getString("temp"));
TextView displayTemp = (TextView) findViewById(R.id.container);
displayTemp.setText(temp);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
我只想尝试获取温度并更新textview。感谢
答案 0 :(得分:2)
检查出来
private class TestTask extends AsyncTask<String,Integer,Boolean>{
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
}
@Override
protected Boolean doInBackground(String... params) throws Exception{
return null;
}
}
这是AsyncTask源中的方法
/**
* Override this method to perform a computation on a background thread. The
* specified parameters are the parameters passed to {@link #execute}
* by the caller of this task.
*
* This method can call {@link #publishProgress} to publish updates
* on the UI thread.
*
* @param params The parameters of the task.
*
* @return A result, defined by the subclass of this task.
*
* @see #onPreExecute()
* @see #onPostExecute
* @see #publishProgress
*/
protected abstract Result doInBackground(Params... params);
注意它不会抛出异常,因此在那里使用“throws Exception”意味着你没有覆盖超类方法并与之发生冲突。
答案 1 :(得分:0)
您只需将doInBackgrond() throws Exception
更改为doInBackground(Void... params)
答案 2 :(得分:0)
将@Override添加到doInBackground方法,当您扩展AsyncTask时,至少必须覆盖doInBackground方法。
删除投掷。
据说doInBackground不是你的“doInBackgrond”错字