AndroidKotlinNullPointerException in Strings

tyu7yeag  于 2023-04-12  发布在  Kotlin
关注(0)|答案(4)|浏览(202)

我正在制作一个应用程序,在这个应用程序中,我在strings.xml文件中写入了国家名称。我想在我的Utils类中获得这些国家名称,但我无法获得这些字符串。如果您能帮助我,我会很高兴。我的代码如下:

class Utils {

    private var resources: Resources? = null
    private val utils = resources!!

    fun getAsiaCountriesFlags(): MutableList<Flag> {
        return mutableListOf(
            Flag(
                R.drawable.asia_turkey,
                listOf(
                    utils.getString(R.string.asia_armenia),
                    utils.getString(R.string.asia_iran),
                    utils.getString(R.string.asia_turkey),
                    utils.getString(R.string.asia_azerbaijan)
                ),
                utils.getString(R.string.asia_turkey)
            )
        )
    }
}

private瓦尔utils = resources!!它在这一行给了我一个错误。我得到的错误是这样的:

Process: com.example.flagquizapp, PID: 8949
    java.lang.NullPointerException
        at com.example.flagquizapp.util.Utils.<init>(Utils.kt:10)
xurqigkl

xurqigkl1#

您的resources对象没有初始化,因此您应该在类构造函数或方法中获取它
类内构造函数

class Utils(private val resources: Resources) {

    fun getAsiaCountriesFlags(): MutableList<Flag> {
        ...
    }
}

方法中

class Utils {

    fun getAsiaCountriesFlags(resources: Resources): MutableList<Flag> {
        ...
    }
}
vcudknz3

vcudknz32#

**Before** 
<string-array name="country_array">

    <item>asia_armenia</item>
    <item>asia_iran</item>
    <item>asia_turkey</item>
    <item>asia_azerbaijan</item>
    <item>asia_turkey</item>

    </string-array>
**Create res--> Array.xml**
**After**
  var categories: Array<String?>
        categories=getResources().getStringArray(R.array.vehiclescategory_array);
yhxst69z

yhxst69z3#

考虑以下情况:
私有var资源:资源?= null
private瓦尔utils = resources?:”“你说什么?”

aiazj4mn

aiazj4mn4#

class Utils(private val context: Context) {

// NOT NEEDED
//private var resources: Resources? = null

// Create Utils class by passing context and
// it'll Lazily initialized utils variable on first call/access
private val utils by lazy { context.resources }

fun getAsiaCountriesFlags(): MutableList<Flag> {
    return mutableListOf(
        Flag(
            R.drawable.asia_turkey,
            listOf(
                utils.getString(R.string.asia_armenia),
                utils.getString(R.string.asia_iran),
                utils.getString(R.string.asia_turkey),
                utils.getString(R.string.asia_azerbaijan)
            ),
            utils.getString(R.string.asia_turkey)
        )
    )
}
}

相关问题