应用类:getDefaultHostName() NullPointerException

问题描述 投票:0回答:1

启动应用程序时,我试图创建首选项并编辑其值,getDefaultHostName() 方法抛出空指针异常。下面,有一个代码示例,如果有人可以提供帮助。谢谢..

private val sContext: MyApp? = null
private fun isEmulator(): Boolean {
        return ((Build.FINGERPRINT.startsWith("sdk_gphone_x86")
                || Build.FINGERPRINT.startsWith("unknown")
                || Build.MODEL.contains("google_sdk")
                || Build.MODEL.contains("Emulator")
                || Build.MODEL.contains("Android SDK built for x86")
                || Build.MANUFACTURER.contains("Genymotion")) || Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith(
            "generic"
        ) || "google_sdk" == Build.PRODUCT || Build.PRODUCT.startsWith("sdk")
                || Build.PRODUCT.startsWith("vbox"))
    }
override fun onCreate() {
        super<Application>.onCreate()
        /*Vid*/
        instance = this
        try {
            val pi = packageManager.getPackageInfo(packageName, 0)
            instance.sAppVersion = pi.versionName
            if (TextUtils.isEmpty(instance.sAppVersion)) {
                instance.sAppVersion = BuildConfig.VERSION_NAME
            }
            instance.sAppBuild = pi.versionCode
            if (instance.sAppBuild <= 0) {
                instance.sAppBuild = BuildConfig.VERSION_CODE
            }
        } catch (e: PackageManager.NameNotFoundException) {
            Log.w(MyApp.TAG, "Failed to retrieve app version", e)
        }
        // Check if preferences already exist. If not, create them.
        val pref = PreferenceManager.getDefaultSharedPreferences(this)
        if (TextUtils.isEmpty(pref.getString(Utils.PREFS_HOST_NAME, null))) {
            // No preferences found. Save default values.
            val editor = pref.edit()
            editor.putString(Utils.PREFS_HOST_NAME, getDefaultHostName())
            editor.putBoolean(Utils.PREFS_USE_TLS, getDefaultTLS())
            editor.apply()
        }
    }
fun getDefaultHostName(): String {
        return sContext!!.resources
            .getString(if (isEmulator()) R.string.emulator_host_name else R.string.default_host_name)
    }
android kotlin nullpointerexception
1个回答
0
投票

sContext 已声明但未在代码中分配值,因此当您调用 getDefaultHostName() 方法并尝试访问 sContext 时,它会抛出错误 NullPointerException.

试试这个来修复错误:

private val sContext: Context = applicationContext

此外,您可能需要检查 getDefaultHostName() 方法是否返回预期的正确值,因为这可能是另一个错误来源。

© www.soinside.com 2019 - 2024. All rights reserved.