[英]Weakreference get null in async task
我在asynctask中使用Weakreferences进行回调。 在asynctask的构造函数中,我给出了一个带有引用的列表。 在我的情况下,列表包含3个引用,2个片段引用和1个Java类引用。
当我检查asynctask的构造函数收到的列表时,该列表包含3个(填充的)引用。 我将它们复制到本地列表(在asynctask中)。 当我检查此列表时,它也有3个(填充的)引用。
然后执行asynctask(doInBackground),不要触摸引用。 当我在doInBackground方法的第一行使用断点检查引用时,第3个(java类)引用为null。 其他2个参考文献仍然填写。
到明天一切正常。 我检查了代码上的差异,但没有太大的差异。 我试图将其回滚,但没有结果。 有人对此有解释吗?
我以这种方式创建了引用: WeakReference<e_Alerts> wr = new WeakReference<e_Alerts>(this); callbackReferences.add(new WeakReference<>((e_Alerts)tab_AlertListOverviewFragment)); callbackReferences.add(new WeakReference<>((e_Alerts)tab_AlertMapsOverviewFragment));
WeakReference<e_Alerts> wr = new WeakReference<e_Alerts>(this); callbackReferences.add(new WeakReference<>((e_Alerts)tab_AlertListOverviewFragment)); callbackReferences.add(new WeakReference<>((e_Alerts)tab_AlertMapsOverviewFragment));
我使用的列表是一个简单的List<WeakReference<e_Alerts>> callbackReferences;
清单。
-------------------------------------------------- ------更新------------------------------------------- -------------
doInBackground代码:
try {
//Downloads the alert XMLs from the internet and parses it to xmlAlerts
this.alerts = new XmlDownloader().DownloadAlerts(inputUrl);
// Filters the xml alerts so only the alerts where the enduser is interessed in will remain
this.alerts = filterAlerts(this.alerts);
// Converts the remaining xmlAlerts to Alerts;
this.result = new AlertConverter().Convert(this.alerts);
}catch (Exception e) {
Log.e("At_allAlerts",e.getMessage());
}
return null;
filterAlerts方法:
private List<Item> filterAlerts(List<Item> alerts) {
List<Item> filteredXmlAlerts = new ArrayList<>();
for (Item alert : alerts)
{
Location alertLocation = new Location("");
alertLocation.setLatitude(alert.getGeometries().get(0).getLocations().get(0).getLat());
alertLocation.setLongitude(alert.getGeometries().get(0).getLocations().get(0).getLng());
for(Area area : this.areas)
{
if (area.IsOrganization() && alert.getCountryCode().toLowerCase().equals(area.getOrganizationcode().toLowerCase())){
filteredXmlAlerts.add(alert);
break;
}
else if(!area.IsOrganization() && isAlertInRegion(alertLocation, area)) {
filteredXmlAlerts.add(alert);
break;
}
}
}
return filteredXmlAlerts;
}
XmlDownloader:下载xml提要,然后使用库将xml解析为对象
AlertConverter:将xml对象转换为我在我的应用中使用的对象
这两个类都可以在没有asynctask类的情况下工作,并且不使用引用。
垃圾收集器可以在没有“强”引用的情况下释放/清空对象。 可能是您使用的变量没有任何引用的情况
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.