微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

android.content.res.Resources android.content.Context.getResources空问题

如何解决android.content.res.Resources android.content.Context.getResources空问题

我创建了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 举报,一经查实,本站将立刻删除。