Can i get the name of the json object from same json object in kotlin?

Viewed 74

I tried to update the sharePreference value using json object. First I create the json object with name, then update the object in sharedPreference. But, I unable to get the json object name. Please help me.

 team1.put("name", "India")
 updateData(team1)

 private fun updateData(data: JSONObject) {
    val sharedPref: SharedPreferences = getSharedPreferences("SharedPref1", 0)
    val editor:SharedPreferences.Editor =  sharedPref.edit()
    editor.putString("JSONObjectName",data.toString()) // How to get the JSONObject name?

} 

I want to like this, data.name == team1.

1 Answers

Referring to your code, you're looking to get the attribute named 'name'. Right ?

You juste have to do this way:

private fun updateData(data: JSONObject) {

    val name = data.getString("name")

    val sharedPref: SharedPreferences = getSharedPreferences("SharedPref1", 0)
    val editor:SharedPreferences.Editor =  sharedPref.edit()

    editor.putString("JSONObjectName", name)
}

Don't forget to check if your JSONObject contains an attribute called 'name' before accessing it to avoid crash ;)

Related