I am new at this Kotlin language when doing Android Studio and I was working on the code and I was stuck on how to combine Shared Preferences with data structures such as (Array List) though so that I can store an array of data. I was wondering if there any way how I can able to do solve this problem? Any suggestion?
class CreateAccount : AppCompatActivity() {
private lateinit var btnCreateAccount: Button
private lateinit var userName : EditText
private lateinit var fullName: EditText
private lateinit var email: EditText
private lateinit var password: EditText
private lateinit var confirmPassword: EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_create_account)
btnCreateAccount= findViewById(R.id.buttonCreateAccount)
email = findViewById(R.id.editTextEmailAddress)
confirmPassword = findViewById(R.id.editConfirmPassword)
password = findViewById(R.id.editPassword)
userName = findViewById(R.id.editTextUserName)
fullName = findViewById(R.id.editTextPersonName)
btnCreateAccount.setOnClickListener {
validateEmptyForm()
}
}
private fun validateEmptyForm(){
if(fullName.text.toString().isNotEmpty() && userName.text.toString().isNotEmpty() && email.text.toString().isNotEmpty() && password.text.toString().isNotEmpty() && confirmPassword.text.toString().isNotEmpty()){
//Need a valid Email to work (ex. [email protected])
if(email.text.toString().matches(Regex("[a-zA-Z0-9._]+@[a-z].+[a-z]"))) {
if (password.text.toString() == confirmPassword.text.toString()) {
Toast.makeText(this, "Created Account Successful!", Toast.LENGTH_LONG).show()
saveData()
val intent = Intent(this,MainActivity::class.java)
startActivity(intent)
}
}
else{
email.setError("Please Enter a Valid Email")
}
}
else{
Toast.makeText(this,"Need to All Information",Toast.LENGTH_SHORT).show()
}
}
private fun saveData(){
//Save user Info, but not stored?
val sharedPref = getSharedPreferences("UserAccount",Context.MODE_PRIVATE)
val edit = sharedPref.edit()
edit.putString("Name", fullName.text.toString())
edit.putString("User Name", userName.text.toString())
edit.putString("Email",email.text.toString())
edit.putString("Password",password.text.toString())
edit.apply()
Toast.makeText(this,"Data has been saved",Toast.LENGTH_LONG).show()
}
}
2
Answers
There are 3 ways to store data on android.
Each way has different strengths and weaknesses
Method 1: Store through share preference
Method 2: Store through database room
Method 3: Online storage of this requires a server
What Tenfour04 said. yup
This is extension I did for class(Mood) objects: