[英]How to propagate Exception message to Activity?
I am using several layers of classes to fetch data from internet and display in Android app. 我正在使用几层类从互联网获取数据并在Android应用中显示。
Activity - ViewModel - Repository - NetworkDataSource ----// Internet 活动-ViewModel-存储库-NetworkDataSource ---- // Internet
I handle HTTP error messages in NetworkDataSource, where I have try/catch block. 我在有try / catch块的NetworkDataSource中处理HTTP错误消息。 However, I would like to propagate this error message to Activity, where I would display a Toast.
但是,我想将此错误消息传播到“活动”,在此我将显示一个Toast。
How to fire an event in the Activity from NetworkDataSource class? 如何在NetworkDataSource类的Activity中触发事件?
static String getResponseFromHttpUrl(URL url) throws IOException {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
String response = "";
try {
urlConnection.setConnectTimeout(5000);
int responseCode = urlConnection.getResponseCode();
switch (responseCode) {
case HttpURLConnection.HTTP_OK:
response = getPayload(urlConnection);
break;
case HttpURLConnection.HTTP_UNAVAILABLE:
throw new IOException("HTTP_UNAVAILABLE");
case HttpURLConnection.HTTP_NOT_FOUND:
throw new IOException("HTTP_NOT_FOUND");
case HttpURLConnection.HTTP_GATEWAY_TIMEOUT:
throw new IOException("HTTP_GATEWAY_TIMEOUT");
}
} catch (IOException e) {
Log.v(TAG, e.getMessage());
throw new IOException(e.getMessage());
} finally {
urlConnection.disconnect();
}
return response;
}
You can use the eventbus. 您可以使用事件总线。 BY eventbus you can send event and can receive ay anyplace you want in the app on whichever thread you want.
通过事件总线,您可以发送事件,并可以在应用程序中的任何位置接收所需的任何线程。
https://github.com/greenrobot/EventBus https://github.com/greenrobot/EventBus
正如Kirtan指出的那样,除了EventBus外,还可以使用接口回调/ RxJava。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.