0

I'm trying to save user data via a Player class as seen below:

class Player(name: String, age: Int, gender: String) {

}

and I'm wondering what the best way to save the class instances is. I think internal storage fits best as it's internal app data that the user doesn't need to directly access.

However there are not many resources that explain saving class instances - I only see examples of saving key-value pairs.

Code:

import kotlinx.android.synthetic.main.activity_player_details.*


class PlayerDetails : AppCompatActivity(), View.OnClickListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_player_details)

        val intent = getIntent()
        val players = intent.getIntExtra("number_of_players", 1)
        println(players)

        next_details.setOnClickListener(this)
    }

    override fun onClick(v: View?) {

        val name: String = player_name.text.toString()

        val age = if (player_age.text.toString().isNotEmpty()) player_age.text.toString().toInt() else 0
        val genderId: Int = gender.checkedRadioButtonId
        val gender: String = if (genderId > 0) resources.getResourceEntryName(genderId) else ""

        if (name.isNotEmpty() && genderId > 0 && age > 0 ){
            println(name)
            println(age)
            println(gender)

            val player = Player(name, age, gender) // I WANT TO SAVE THIS INSTANCE
        } else {
            blankFields()
        }
    }

    private fun blankFields() {
        blank_fields_error.visibility = View.VISIBLE
    }

}

Any advice appreciated.

Zorgan
  • 8,227
  • 23
  • 106
  • 207

1 Answers1

1

Basically what you're asking is called "serialization".

In Android you have several ways to serialize an object for storage:

  • Use Java standard serialization (not recommended). Note that this requires a binary storage (e.g. database BLOB) or be converted to Base64 to store in a text format.
  • Use a serialization library, e.g. JSON, YAML, etc... This is going to be several magnitudes slower that a binary serialization (Android's Parcelable or Java's Serializable), and also slower than binary + Base64, so in my opinion not really a valid option unless you absolutely want the data stored to be human-readable.

Note that Parcelable is not suitable for consitent storage, so it is not an option.

Note that however, in my experience, I tested a lot of serialization methods (mainly for for IPC) and Serializable was fast enough without adding all the bloated code to use Parcelable. Parcelable only provided a negligible speed gain not worth the hassle of implementing and correctly maintaining Parcelable classes.

m0skit0
  • 25,268
  • 11
  • 79
  • 127