我在学习如何使用AsyncTask。我有返回一个String数组的doInBackground
中的代码,以及调用接口将其返回给MainActivity的回调。我正在成功执行AsyncTask。在AsyncTask中重写onPostExecute()
问题是:试图通过onPostExecute返回数组我得到一个参数错误;它不会接受数组。如何使用onPostExecute
方法返回值feeds
?我试图改变doInBackground
的结果,但是也不接受数组。
这里称为MainActivity接口:
interface DownloadFinishedListener {
void notifyDataRefreshed(String[] feeds);}
这里是回调:
try {
mCallback = (DownloadFinishedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement DownloadFinishedListener");
}
这里是的AsyncTask:
public class DownloaderTask extends AsyncTask<Integer, Void, String> {
@Override
protected String doInBackground(Integer... params) {
downloadTweets(params);
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
mCallback.notifyDataRefreshed(s); //trying to send back feeds
}
// Simulates downloading Twitter data from the network
private String[] downloadTweets(Integer resourceIDS[]) {
final int simulatedDelay = 2000;
String[] feeds = new String[resourceIDS.length];
try {
for (int idx = 0; idx < resourceIDS.length; idx++) {
InputStream inputStream;
BufferedReader in;
try {
// Pretend downloading takes a long time
Thread.sleep(simulatedDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
inputStream = mContext.getResources().openRawResource(
resourceIDS[idx]);
in = new BufferedReader(new InputStreamReader(inputStream));
String readLine;
StringBuffer buf = new StringBuffer();
while ((readLine = in.readLine()) != null) {
buf.append(readLine);
}
feeds[idx] = buf.toString();
if (null != in) {
in.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return feeds;
}
}
谢谢。我曾尝试使用'String ...',这给了我各种各样的错误。 'String []'似乎已经处理了,以及其他建议的编辑。 – DevJem 2015-04-06 11:10:23
我可以在第二点获得解释吗?如果你调用'downloadTweets(params); return downloadTweets(params);'这将调用该方法两次,对吧? – DevJem 2015-04-06 11:27:01
@Dithanial:是的,从downloadTweets方法返回的'doInBackground'返回String []数组方法 – 2015-04-06 12:21:50