安卓实现笔记本app

本文展示了如何使用Jetpack Compose、ViewModel和Room数据库构建一个简单的笔记应用程序。通过300行代码实现笔记的增删改查功能,包括笔记列表和详情页面。应用采用单例模式的Room数据库,存储库层提供统一接口,ViewModel负责数据管理,Compose用于UI构建。
摘要由CSDN通过智能技术生成

简介

本文实现一个简单的笔记本app,每个笔记有标题和内容,笔记本首页可以浏览有哪些笔记和添加笔记,笔记详情页可以编辑删除笔记。
本app使用Compose + ViewModel + Room实现,阅读此文前可以先去了解这几个框架。由于使用了这些框架,我们只需不到300行代码即可实现我们的记事本app。
整个app结构如下:
Compose - Activity - ViewModel - Repository - RoomDatabase

数据库

首先使用room来定义我们的数据库。
我们只需要存储笔记,每个笔记有标题和内容,其实体定义如下:

@Entity
data class Note(
   @PrimaryKey(autoGenerate = true) val id: Long,
   val title: String,
   val content: String,
) : Serializable

接下来是定义我们的dao:

@Dao
interface NoteDao {
    @Insert
    suspend fun insert(note: Note): Long

    @Insert
    suspend fun insertAll(vararg note: Note)

    @Update
    suspend fun update(note: Note)

    @Delete
    suspend fun delete(note: Note)

    @Query("DELETE FROM Note")
    suspend fun deleteAll()

    @Query("SELECT * FROM Note")
    fun getAll(): Flow<List<Note>>
}

虽然NoteDao只是一个interface,但是有@Dao注解,room会为我们自动实现具体方法。

然后定义我们的数据库:

@Database(entities = [Note::class], version = 1)
abstract class NoteDatabase : RoomDatabase() {
    abstract fun noteDao(): NoteDao

    companion object {
        @Volatile
        private var INSTANCE: NoteDatabase? = null

        fun getInstance(context: Context, scope: CoroutineScope): NoteDatabase {
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(context.applicationContext,
                    NoteDatabase::class.java,
                    "note_database")
                    .build()
                INSTANCE = instance
                instance
            }
        }
    }
}

数据库是单例模式,确保同一个进程只创建一个NoteDatabase对象。

存储库

数据库定义完成后,就可以创建我们的存储库了,存储库十分简单,定义如下:

class NoteRepository(private val noteDao: NoteDao) {
    val allNotes: Flow<List<Note>> = noteDao.getAll()

    suspend fun insert(note: Note): Long {
        return noteDao.insert(note)
    }

    suspend fun update(note: Note) {
        return noteDao.update(note)
    }

    suspend fun delete(note: Note) {
        return noteDao.delete(note)
    }
}

有了存储库,ViewModel就可以通过存储库访问数据库了。

可能大家会有疑问为什么需要存储库,ViewModel直接访问dao来访问数据库不就可以了吗?
其实存储库这层一般还是有意义的,其可以给所有数据源提供统一接口,例如有的数据可能来自于网络。所以存储库的意义在于上层可以统一通过存储库来访问不同来源的数据。

ViewModel

有了存储库,我们就可以创建我们的ViewModel了,其定义如下:

class NoteViewModel(private val noteRepository: NoteRepository) : ViewModel() {
    val allNotes: LiveData<List<Note>> = noteRepository.allNotes.asLiveData()

    fun insertBlock(note: Note): Note = runBlocking {
        val id = noteRepository.insert(note)
        return@runBlocking Note(id, note.title, note.content)
    }

    fun insert(note: Note) = viewModelScope.launch {
        noteRepository.insert(note)
    }

    fun upate(note: Note) = viewModelScope.launch {
        noteRepository.update(note)
    }

    fun delete(note: Note) = viewModelScope.launch {
        noteRepository.delete(note)
    }
}

class NoteViewModelFactory(private val noteRepository: NoteRepository) : ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(NoteViewModel::class.java)) {
            return NoteViewModel(noteRepository) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}

有了ViewModel,Activity就可以通过其访问数据库了。

可能大家会有疑问为什么需要ViewModel,Activity直接通过存储库来访问数据库不就可以了吗?
ViewModel的意义在于存储了界面数据,并且不受Activity的生命周期和配置更新所影响,这样就可以让Activity只关注绘制界面,而ViewModel只关注界面数据。如果没有ViewModel,Activity每次重启重新去读数据库就会浪费大量资源。

界面

有了ViewModel就可以构建我们的界面了,首先实现笔记本首页NotebookActivity,其可以展示目前所有的笔记,相当于是所有笔记的目录,我们对于每个笔记只显示其标题,并且还有添加笔记按钮,其实现如下:

class NotebookActivity : AppCompatActivity() {
    private val noteViewModel: NoteViewModel by viewModels { NoteViewModelFactory((application as NotebookApplication).noteRepository) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MainContent(noteViewModel)
        }
    }

    companion object {
        fun actionStart(context: Context) {
            val intent = Intent(context, NotebookActivity::class.java)
            context.startActivity(intent)
        }
    }
}

@Preview
@Composable
private fun PreviewContent() {
    RootContent(notes = listOf(Note(1, "11", "111"),
        Note(2, "22", "222"),
        Note(3, "33", "333"),), {Note(0, "", "")})
}

@Composable
private fun MainContent(noteViewModel: NoteViewModel) {
    val notes by noteViewModel.allNotes.observeAsState(listOf())
    RootContent(notes, { noteViewModel.insertBlock(Note(0, "Title", "Content")) })
}

@Composable
private fun RootContent(notes: List<Note>, onAddNote: () -> Note) {
    val context = LocalContext.current
    Scaffold(floatingActionButton = {
        Icon(Icons.Rounded.Add, "New note", Modifier.size(100.dp).clickable {
            val note = onAddNote()
            NoteActivity.actionStart(context, note)
        })
    }, content = {
        NoteList(notes = notes)
    })
}

@Composable
private fun NoteList(notes: List<Note>) {
    val context = LocalContext.current
    LazyColumn {
        items(notes) { note ->
            Text(text = note.title,
                Modifier.fillMaxWidth()
                    .padding(all = 30.dp)
                    .clickable { NoteActivity.actionStart(context, note) })
        }
    }
}

NotebookActivity可以跳转到笔记详情页NoteActivity,其实现如下:

class NoteActivity : AppCompatActivity() {
    private val noteViewModel: NoteViewModel by viewModels { NoteViewModelFactory((application as NotebookApplication).noteRepository) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val note = intent.extras!!["note"] as Note
        setContent {
            MainContent(note, noteViewModel)
        }
    }

    companion object {
        fun actionStart(context: Context, note: Note) {
            val intent = Intent(context, NoteActivity::class.java)
            intent.putExtra("note", note)
            context.startActivity(intent)
        }
    }
}

@Preview
@Composable
private fun PreviewContent() {
    RootContent(note = Note(1, "title", "content"), {}, {})
}

@Composable
private fun MainContent(note: Note, noteViewModel: NoteViewModel) {
    RootContent(note, { note -> noteViewModel.upate(note) }, { note -> noteViewModel.delete(note) })
}

@Composable
private fun RootContent(note: Note, onNoteChange: (note: Note) -> Unit, deleteNote: (note: Note) -> Unit) {
    val activity = LocalContext.current as Activity
    var openConfirmDeleteDialog by remember { mutableStateOf(false) }
    Column {
        var title by remember { mutableStateOf(note.title) }
        var content by remember { mutableStateOf(note.content) }
        Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
            TextField(value = title, onValueChange = { title = it; onNoteChange(Note(note.id, title, content)) }, Modifier.weight(7f))
            Icon(Icons.Filled.Delete, "Delete note",
                Modifier.weight(1f).clickable { openConfirmDeleteDialog = true })
        }
        TextField(value = content, onValueChange = { content = it; onNoteChange(Note(note.id, title, content)) }, Modifier.fillMaxSize())
    }
    if (openConfirmDeleteDialog) {
        AlertDialog(onDismissRequest = { openConfirmDeleteDialog = false },
            title = { Text("Confirm delete note") },
            confirmButton = { Button(onClick = { openConfirmDeleteDialog = false; deleteNote(note); activity.finish() }) { Text("Delete") } },
            dismissButton = { Button(onClick = { openConfirmDeleteDialog = false }) { Text("Dismiss") } })
    }
}

每次笔记被编辑,其标题或内容文本发生变化后都去存入数据库,实现了笔记的实时保存,因此不需要再设计一个保存按钮了。

总结

完整源码地址:https://github.com/SSSxCCC/SCApp
Compose框架省去了编写xml,Room构建数据库省去了大量繁琐的SQL语句的编写,最终只用了少量代码实现了增删改功能的笔记本app。

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SSSxCCC

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值