SharedPreferences 실제로 사용하기.
1. main.xml 그리기
<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">
<EditText
android:id="@+id/editTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
android:textColor="@color/black"
android:ems="10"
android:inputType="textPersonName"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/saveBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="저장하기"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editTxt" />
</androidx.constraintlayout.widget.ConstraintLayout>
2.MainActivity 코딩
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.example.sharedpreferences.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
lateinit var binding : ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
binding.saveBtn.setOnClickListener {
saveData()
Toast.makeText(this,"데이터가 저장 되었습니다.",Toast.LENGTH_SHORT).show()
}
loadData()
}
private fun saveData() {
val pref = getSharedPreferences("pref",0)
val edit = pref.edit() //수정 모드
// 1번째 인자는 키 , 2번째 인자는 실제 담아둘 값
edit.putString("name",binding.editTxt.text.toString())
edit.apply() //저장 완료
}
private fun loadData() {
val pref = getSharedPreferences("pref" , 0)
// 1번째 인자는 키, 2번째 인자는 데이터가 존재하지 않을 경우의 값
binding.editTxt.setText(pref.getString("name",""))
}
}
- device file exploer 들어가서 데이터 저장된거 확인가능!