界面布局
App 本地数据存储有几种方式,按数据大小和用途选:SharedPreferences 存配置、文件存数据、SQLite/Room 存结构化数据。
SharedPreferences
存键值对(登录状态、设置项)。getSharedPreferences + edit + apply/commit。
Room 数据库
官方 ORM:Entity 定义表,DAO 定义增删改查,Database 管理。用协程异步操作,避免主线程卡顿。
文件
filesDir 私有目录存文件,cacheDir 缓存目录(系统可清)。
代码示例
// SharedPreferences 存配置
val sp = getSharedPreferences("app_config", MODE_PRIVATE)
sp.edit().putString("nickname", "张三").apply()
val nick = sp.getString("nickname", "默认名")
// Room 实体
@Entity(tableName = "notes")
data class Note(
@PrimaryKey(autoGenerate = true) val id: Long = 0,
val title: String,
val content: String
)
// Room DAO
@Dao
interface NoteDao {
@Query("SELECT * FROM notes ORDER BY id DESC")
suspend fun getAll(): List<Note>
@Insert
suspend fun insert(note: Note)
}