使用asynctask的代码有什么问题?尤其: - 我需要放入哪些参数 - 我需要放入哪些参数?
我找到了很多"有用的"示例,但是它们都在这些参数中使用了伪代码,并且不解释我实际需要放在那里。
"我得到日食错误。
我不需要传递任何东西,我希望它返回字符串。
public class fetchSchools extends AsyncTask<Void, Void, String> {
public String doInBackground(String retval) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.domain/schools.php");
try
{
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String
line;
int a=0;
while ((line = reader.readLine()) != null) {
builder.append(line);
Log.i(MainActivity.class.getName(), "Reading in: " + a +" : "+ line);
a++;
}
} else {
Log.e(MainActivity.class.toString(), "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
return builder.toString();
}
protected void onPostExecute() {
}
}
您给了doinbackground一个字符串参数,因此async任务第一个参数必须是字符串而不是void。
AsyncTask<String , Void, String> {
如果您不想传递参数,请不要给参数doinbackground函数。
选中此页面以获取异步参考:http://developer.android.com/reference/android/os/asynctask.html
asynctask的第一个参数转到doinbackground函数,第二个参数转到onprogressupdate函数,第三个参数foes到OnPostExecute函数。
我认为您想这样做:
public class fetchSchools extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... arg0) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
// ...
return builder.toString();
}
protected void onPostExecute(String retval)
{
}
}
我不需要传递任何东西,我希望它返回字符串。
然后
public class fetchSchools extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
// ...
}
}