《第一行代码》第七章 数据持久化
程序员文章站
2022-08-18 12:21:51
7.2 文件存储7.2.1 将数据存储到文件中...
7.2 文件存储
7.2.1 将数据存储到文件中
输入一些信息,然后按back键退出.
按下快捷键 Ctrl + Shift + A, 在搜索框输入Device File Explorer (或者在Android Studio右下角找) 在data/data/com.example.<项目名称>/files/ 的目录下可以找到一个data文件。
7.2.2 从文件中读取数据
退出后重新进入
MainActivity.kt
package com.example.persistence_7_1
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import java.io.*
import java.lang.StringBuilder
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val inputText = load()
if (inputText.isNotEmpty()) {
editText.setText(inputText)
editText.setSelection(inputText.length)
Toast.makeText(this, "Restoring succeeded", Toast.LENGTH_SHORT).show()
}
}
override fun onDestroy() {
super.onDestroy()
val inputText = editText.text.toString()
save(inputText)
}
private fun save(inputText: String){
try{
val output = openFileOutput("data", Context.MODE_PRIVATE)
val writer = BufferedWriter(OutputStreamWriter(output))
writer.use{
it.write(inputText)
}
} catch (e: IOException) {
e.printStackTrace()
}
}
private fun load(): String {
val content = StringBuilder()
try{
val input = openFileInput("data")
val reader = BufferedReader(InputStreamReader(input))
reader.use {
reader.forEachLine {
content.append(it)
}
}
} catch (e: IOException) {
e.printStackTrace()
}
return content.toString()
}
}
activity_main.xml和7.2.1一样
<?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">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Type something here"
tools:ignore="HardcodedText" />
</androidx.constraintlayout.widget.ConstraintLayout>
7.3 SharedPreferences存储
7.3.1-7.3.2 SharedPreferences存储和读取数据
点击save data按钮
在/data/data/com.example.<项目名>/shared_preds/ 目录下
点击restore data按钮
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/saveButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Save Data"
tools:ignore="HardcodedText" />
<Button
android:id="@+id/restoreButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Restore Data"
tools:ignore="HardcodedText" />
</LinearLayout>
MainActivity.kt
package com.example.persistence_7_1
import android.annotation.SuppressLint
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import java.io.*
import java.lang.StringBuilder
class MainActivity : AppCompatActivity() {
@SuppressLint("CommitPrefEdits")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
saveButton.setOnClickListener{
val editor = getSharedPreferences("data", Context.MODE_PRIVATE).edit()
editor.putString("name", "Tom")
editor.putInt("age", 28)
editor.putBoolean("married", false)
editor.apply()
Toast.makeText(this, "Save data successfully", Toast.LENGTH_SHORT).show()
}
restoreButton.setOnClickListener{
val prefs = getSharedPreferences("data", Context.MODE_PRIVATE)
val name = prefs.getString("name", "")
val age = prefs.getInt("age", 0)
val married = prefs.getBoolean("married", false)
Log.d("MainActivity", "name is $name")
Log.d("MainActivity", "age is $age")
Log.d("MainActivity", "married is $married")
}
}
}
7.3.3 实现记住用户名和密码的功能
这里我们拿6.4强制实现下线功能的项目再进行改进.先看看效果
退出后会发现用户名密码都在,然后复选框也被选上了。
主要改动的两个文件的代码:
activity_login.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="60dp">
<TextView
android:layout_width="90dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:textSize="18sp"
android:text="Account:" />
<EditText
android:id="@+id/accountEdit"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center_vertical" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="60dp">
<TextView
android:layout_width="90dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:textSize="18sp"
android:text="Password:"
tools:ignore="HardcodedText" />
<EditText
android:id="@+id/passwordEdit"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center_vertical"
android:inputType="textPassword" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<CheckBox
android:id="@+id/rememberPass"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:text="Remember password"
tools:ignore="HardcodedText" />
</LinearLayout>
<Button
android:id="@+id/login"
android:layout_width="200dp"
android:layout_height="60dp"
android:layout_gravity="center_horizontal"
android:text="Login"
tools:ignore="HardcodedText" />
</LinearLayout>
LoginActivity.kt
package com.example.broadcasttest
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_login.*
class LoginActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
// 7.3.3 更改部分1(共两部分)start
val prefs = getPreferences(Context.MODE_PRIVATE)
val isRemember = prefs.getBoolean("remember_password", false)
if(isRemember) {
// 获取已经保存的账号和密码
val account = prefs.getString("account", "")
val password = prefs.getString("password", "")
// 账号和密码都设置到文本框里面
accountEdit.setText(account)
passwordEdit.setText(password)
// 将记住密码的checkBox选上
rememberPass.isChecked = true
}
// end of updated part1
login.setOnClickListener {
val account = accountEdit.text.toString()
val password = passwordEdit.text.toString()
//用户名是admin,密码是123456
if (account == "admin" && password == "123456"){
// 7.3.3 更改部分2(共两部分)start
val editor = prefs.edit()
// 检查复选框是否被选中
if(rememberPass.isChecked){
// 将记住密码的状态和用户名密码保存起来,实际开发项目中还要加密
editor.putBoolean("remember_password", true)
editor.putString("account", account)
editor.putString("password", password)
} else {
editor.clear()
}
editor.apply()
// end of updated part2
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
} else {
Toast.makeText(this, "account or password is invalid", Toast.LENGTH_SHORT).show()
}
}
}
}
7.4 SQLite 数据库存储
7.4.1 创建数据库
本文地址:https://blog.csdn.net/weixin_43850253/article/details/107567633
上一篇: 一向奸诈的曹操因为哪些手下的死而大哭呢?
下一篇: 襄樊之战后,为何刘备没有重新夺回樊城呢?