Thursday, July 9, 2020

Shared Preferences - Kotlin

To save your data

Main Activity code:

class MainActivity : AppCompatActivity() {


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

var editor=getSharedPreferences("button_key",MODE_PRIVATE).edit()

button_switch.setOnClickListener {
//saving data
editor.putBoolean("button_status",button_switch.isChecked)
editor.apply()

//retrieving data
var prefs=getSharedPreferences("button_key",MODE_PRIVATE)
val button_status_textview=prefs.getBoolean("button_status",false)
textView_status.text="button status is $button_status_textview"
}


}

}
Here is the xml Code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/textView_status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Switch
android:id="@+id/button_switch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:layout_marginEnd="32dp"
android:text="Switch"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

demo : you can retrieve  your data from different activity



 



No comments:

Post a Comment

Dilog Builder - Kotlin

Dialog Builder in Kotlin  Set your default dialog in MainActivity demo: After clicking any button you can show dialoug in  button.setOnClick...