问题描述
我创建了Util,用于访问比以前更简单的资源。
它从MyApplication
或上下文中获取资源。
但是,出现空对象引用错误,资源ID为
2020-11-06 13:59:36.665 12563-12563/com.example.sample D/test: id: 2131820930
utils
包中
object ResourcesUtils {
fun getString(context: Context?,@StringRes id: Int): String {
Log.d("test","id: $id")
try{
if(context == null){
return MyApplication.getInstance().resources.getString(id)
}
return context.resources.getString(id)
}catch (e: Exception){
e.printstacktrace()
}
return "N/A"
}
fun getString(@StringRes id: Int): String {
return getString(null,id)
}
}
在utils
包中,
object Utils {
val pmOrAm: String
get() {
val var0 = System.currentTimeMillis()
val var2 = Calendar.getInstance()
var2.timeInMillis = var0
return if (var2[Calendar.AM_PM] == 0) ResourcesUtils.getString(R.string.user_hello_am) else ResourcesUtils.getString(R.string.user_hello_pm)
}
}
在strings.xml
<!-- Utils -->
<string name="user_hello_am">Good Morning,</string>
<string name="user_hello_pm">Hello,</string>
MyApplication是
class MyApplication : MultiDexApplication() {
override fun onCreate() {
super.onCreate()
init()
}
private fun init(){
// Todo: init
}
companion object {
@Volatile
private var instance: MyApplication? = null
fun getInstance(): MyApplication {
if (instance == null) {
synchronized(this) {
if (instance == null) {
instance = MyApplication()
}
}
}
return instance!!
}
}
出什么问题了?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)