【发布时间】:2018-05-31 19:50:52
【问题描述】:
我有一个类来显示 HTTP 的错误消息。
根据 throwable 它显示一条消息。
但有时我得到空指针异常
public static void showGeneralErrors(Throwable throwable) {
String message = "";
AppInitialization appInitialization = AppInitialization.getInstance();
if (appInitialization == null) {
return;
}
try {
if (throwable instanceof HttpException) {
if (((HttpException) throwable).code() == 500) {
message = appInitialization.getString(R.string.server_error);
} else {
message = appInitialization.getString(R.string.parsing_problem);
}
} else if (throwable instanceof IOException) {
message = appInitialization.getString(R.string.internet_error);
}else if(throwable instanceof SSLHandshakeException){
message = appInitialization.getString(R.string.internet_error);
}
if (!TextUtils.isEmpty(message)) {
Toast.makeText(appInitialization, message, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Log.e(">>>>>", "Exception network error handler " + e.getMessage());
} catch (IllegalStateException e) {
Log.e(">>>>>", "IllegalStateException network error handler " + e.getMessage());
} catch (NullPointerException e) {
Log.e(">>>>>", "NullPointerException network error handler " + e.getMessage());
}
}
错误信息是:
原因:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法 'android.content.res.Resources android.content.Context.getResources()' 在 android.widget.Toast.makeText(Toast.java:298)
而公共 AppInitialization 是:
public class AppInitialization extends Application {
private static AppInitialization mInstance;
public static synchronized AppInitialization getInstance() {
return mInstance;
}
public void onCreate() {
super.onCreate();
mInstance = this;
}
它来自于改造Onfailure方法:
GeneralRepo.getCountryFromIp(getContext())
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(countryFromIPResponse -> {
//do something
}, throwable -> {
// Where i got error
NetworkErrorHandler.showGeneralErrors(throwable);
});
为什么会出现这个错误以及为什么 try/catch 不起作用?
【问题讨论】:
-
因为您的错误不会在该代码块上触发,请在您的答案中添加更多 logcat 以查看原始错误。
-
同意@diegoveloper,同时检查可抛出对象是否为空
-
@diegoveloper 更新
-
你能把这个代码: AppInitialization.getInstance() ,你的appinitialization类
-
你确定问题出在这段代码上吗?
标签: java android android-resources android-context