首次尝试在主UI线程上进行网络连接时遇到此问题。
然后尝试使用AsyncTask来避免它,但仍然得到相同的异常。
Networkign仅在AsyncTask.doInBackground()
方法内发生。但我仍然得到这个例外。我该如何解决?
public class AsyncRSSLoader extends AsyncTask<Void, Void, RSSData> {
private String url = "http://www.nasa.gov/rss/dyn/image_of_the_day.rss";
@Override
protected RSSData doInBackground(Void... params) {
try {
IotHandler handler = new IotHandler();
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setContentHandler(handler);
InputStream inputStream = new URL(url).openStream();
reader.parse(new InputSource(inputStream));
RSSData data = new RSSData();
data.setDate(handler.getDate());
data.setTitle(handler.getTitle());
data.setImage(getBitmap(handler.getImageUrl()));
return data;
} catch (Exception e) {
e.printStackTrace();
Log.e("NASA_RSS", e.getStackTrace().toString());
}
return null;
}
}
以及这个类的用法:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AsyncRSSLoader loader = new AsyncRSSLoader();
RSSData data = loader.doInBackground();
resetDisplay(data.getTitle(), data.getDate(), data.getImage(), data.getDescription());
}
答案 0 :(得分:1)
你必须致电
loader.doInBackground()
而不是execute()
。 doInBackground
从工作线程调用project.configurations.all {
resolutionStrategy {
force lockForces.toArray()
}
}
。如果需要将数据传递回Activity,请使用委托。您可以找到示例here