Home > database >  Android Kotlin NullPointerException in Strings
Android Kotlin NullPointerException in Strings

Time:12-16

I am making an application, in this application I wrote the country names in strings.xml file. I want to get these country names in my Utils class, but I can't get these strings. I would be glad if you help. My code is below:

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 val utils = resources!! It gives me an error on the this line. The error I'm getting is this:

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

CodePudding user response:

**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);

CodePudding user response:

Your resources object is not initialized so you should get it in the class constructor or method

In Class Constructor

class Utils(private val resources: Resources) {

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

In Method

class Utils {

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