[英]How to externalize the string for an error message in a custom exception class in Android
I have this class 我有这堂课
public class InternetConnectionException extends RuntimeException {
int code = 0;
public InternetConnectionException(){
super("Internet connection is down");
}
public InternetConnectionException(String message){
super(message);
}
}
This error message shouldn't be hardcoded. 此错误消息不应进行硬编码。 It should be externalized in order for different languages to be supplied, because when this exception is thrown the message is being displayed on the screen. 应该将其外部化以提供不同的语言,因为抛出此异常时,消息将显示在屏幕上。 Now, is there a way to externalize it as a strings.xml
resource or should I change the design? 现在,是否有一种方法可以将其外部化为strings.xml
资源,还是应该更改设计? (ie when this exception is thrown, just reference the string resource in the activity and display the resolved value) (即,抛出此异常时,只需在活动中引用字符串资源并显示已解析的值)
I believe that a good design shouldn't allow pure Java classes such as an exception to know about the insides of Android framework, but I could be wrong. 我认为,好的设计不应允许纯Java类(例如异常)知道Android框架的内部,但我可能是错的。
Since you can't access string.xml directly but there is one way I can think of to achieve what you're trying to accomplish. 由于您不能直接访问string.xml,但是我可以想到一种方法来实现您要完成的任务。
Here are some codes to demonstrate the idea 这是一些代码来证明这个想法
AppApplication.java AppApplication.java
public class AppApplication extends Application {
public static StringConstant STRING_CONSTANT;
@Override
public void onCreate() {
super.onCreate();
STRING_CONSTANT = new StringConstant(getBaseContext());
STRING_CONSTANT.build();
}
}
StringConstant.java StringConstant.java
public class StringConstant {
private Context context;
public static String appName;
// declare other String variables
public StringConstant(Context context) {
this.context = context;
}
public void build(){
setAppName(context.getString(R.string.app_name));
// set other String variables
}
public static String getAppName() {
return appName;
}
public static void setAppName(String appName) {
StringConstant.appName = appName;
}
}
and now accessing the strings from another class 现在从另一个类访问字符串
public class InternetConnectionException extends RuntimeException {
int code = 0;
public InternetConnectionException(){
super(AppAplication.STRING_CONSTANT.getAppName());
}
public InternetConnectionException(String message){
super(message);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.