片段上的 onPostExecute(AsyncTask) 中的 ArrayList 为空



我在 Fragment 上使用 onPostExecute(AsyncTask( 中的 ArrayList。

问题是arrivalInfoArrayList在我执行 AsyncTask 后是空的。

我尝试使用

1(

getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
//Code for the UiThread
}
});

2(

new Handler().post(new Runnable() {
@Override
public void run() {
}
});

但它没有奏效。我该如何解决这个问题?这是我的代码。

arrivalAsync = new ArrivalAsync() {
@Override
protected void onPostExecute(String arrivalUrl) {
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader(arrivalUrl));
int eventType = xpp.getEventType();
while(eventType != XmlPullParser.END_DOCUMENT) {
if(eventType == XmlPullParser.START_DOCUMENT) {
} else if(eventType == XmlPullParser.START_TAG) {
String tagName = xpp.getName();
switch (tagName) {
case "arsId":
bl_arsId = true;
break;
case "firstTm":
bl_firstTm = true;
break;
case "lastTm":
bl_lastTm = true;
case "stNm":
bl_stNm = true;
break;
}
} else if(eventType == XmlPullParser.TEXT) {
if(bl_arsId) {
arsId = xpp.getText();
arrivalInfo.setArsId(arsId);
bl_arsId = false;
}
if(bl_firstTm) {
firstTm = xpp.getText();
arrivalInfo.setFirstTm(firstTm);
bl_firstTm = false;
}
if(bl_lastTm) {
lastTm = xpp.getText();
arrivalInfo.setLastTm(lastTm);
bl_lastTm = false;
}
if(bl_stNm) {
stNm = xpp.getText();
arrivalInfo.setStNm(stNm);
bl_stNm = false;
}

} else if(eventType == XmlPullParser.END_TAG) {
String tagName = xpp.getName();
if(tagName.equals("itemList"))  {
arrivalInfoArrayList.add(arrivalInfo);
arrivalInfo = new ArrivalInfo();
}
}
eventType = xpp.next();
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
arrivalAsync.execute(arrivalUrl);

首先,你应该在doInBackround((中循环计算时这样做。此外,您是否尝试在日志中打印数组列表大小或尝试调试执行以检查数组列表中是否添加了任何数据?如果没有,那么你应该做这个基本的家庭作业。

假设arrivalUrl是一个实际的 URL 字符串,并且目的是获取/解析 URL 响应,那么您需要获取到 URL 终结点的输入流,如下所示。 但是您必须在后台执行此操作 -doInBackground.

InputStream is = new URL(arrivalUrl).openConnection().getInputStream();
xpp.setInput(is, null);

并在最后关闭流

is.close();

并用 try-block 包装所有内容以查找可能的异常。

doInBackground返回数组列表并在onPostExecute中处理它。

这里有一个答案可以证明这一点 - 你离它不远 - 基本上把你的onPostExecute变成doInBackground并返回 ArrayList: https://stackoverflow.com/a/6343299/2711811

最新更新