[08] Collection business of Kotlin project practical operation

(1) As long as a person does not give up on himself, the whole world will not give up on you.
(2) I am born to be of great use . (3) If I
cannot bear the suffering of learning, I must endure the suffering of life. How painful it is Deep insight.
(4) You must gain from doing difficult things . (
5) Spirit is the real blade.
(6) Defeating opponents twice, the first time in the heart.
(7) Living well means doing meaningful things.
(8) ) It’s not too late to fix the situation
.
(10) With strength, 365 days a year is the peak season for applicants. Without strength, every day is the off-season for applicants.
(11) The foundation is not strong, the earth is shaken.
(12) The original intention of blogging: grow yourself and help others. When you leave the world one day, I hope that the thoughts in the blog can help people guide the direction.
(13) It is not easy to write, if you like it or it is helpful to you, remember to like + follow or bookmark~

[08] Collection business of Kotlin project practical operation

Article Directory

1.View layer

1.1BaseFragment base class

/**
 * @author XiongJie
 * @version appVer
 * @Package com.gdc.kotlinproject.base
 * @file
 * @Description:所有Fragment的父类
 * @date 2021-6-4 19:14
 * @since appVer
 */
abstract class BaseFragment<P> :Fragment() where P:IBasePresenter{

    //1.presenter对象属性
    lateinit var p:P

    //1.Fragment需要拿到 Activity
    private lateinit var mActivity: AppCompatActivity

    //1.onAttach表示Fragment赋加到Activity上的时候
    override fun onAttach(context: Context) {
        super.onAttach(context)
        // Java
        // mActivity = (AppCompatActivity) context

        // KT
        mActivity = context as AppCompatActivity
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        p = getPresenter()
    }

    //1.由子类具体负责创建
    abstract fun getPresenter() : P

    //1.资源释放
    override fun onDestroy() {
        super.onDestroy()
        recycle()
    }

    //1.
    abstract fun createOK()

    //1.资源释放
    abstract fun recycle()

    //1.隐藏ActionBar
    fun hideActionBar() : Unit{
        val actionBar : ActionBar? = mActivity?.supportActionBar
        actionBar?.hide()
    }

    //1.显示ActionBar
    fun showActionBar() : Unit {
        mActivity?.supportActionBar?.show()
    }
}

1.2 pages

package com.gdc.kotlinproject.modules.collect

import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.Toast
import com.gdc.kotlinproject.R
import com.gdc.kotlinproject.adapter.CollectAdapter
import com.gdc.kotlinproject.base.BaseFragment
import com.gdc.kotlinproject.config.Flag
import com.gdc.kotlinproject.database.Student
import com.gdc.kotlinproject.modules.collect.interfaces.CollectView
import com.gdc.kotlinproject.modules.collect.interfaces.CollectPresenter
import kotlinx.android.synthetic.main.fragment_collect.*

/**
 * @author XiongJie
 * @version appVer
 * @Package com.gdc.kotlinproject.modules.collect
 * @file
 * @Description:View的实现层
 * @date 2021-6-4 18:15
 * @since appVer
 */
class CollectFragment : BaseFragment<CollectPresenter>(),CollectView{

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        Toast.makeText(activity, "收藏", Toast.LENGTH_SHORT).show()
        val root: View? = inflater.inflate(R.layout.fragment_collect, container, false)
        //1.如果root不为空,则使用root,为空,则使用后面的
        return root ?: super.onCreateView(inflater, container, savedInstanceState)
    }

    //类似于java构造代码块
    init {
        //设置菜单
        setHasOptionsMenu(true)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        addData.setOnClickListener{
            val names = arrayOf<String>(
                "乔峰",
                "段誉",
                "虚竹",
                "慕容复",
                "张三",
                "李四",
                "王五",
                "赵六",
                "初七",
                "杜子腾",
                "王小二",
                "李大奇"
            )

            val ages = arrayOf<Int> (
                43,
                24,
                19,
                83,
                64,
                21,
                56,
                32,
                17,
                32,
                45,
                14
            )

            //1.批量插入数据到数据库
            for(index in names.indices){
                val stu = Student(names[index],ages[index])
                p.requestInsert(stu)
            }
        }

        /**
         * 全部删除动作
         */
        clearData.setOnClickListener{
           p.requestDeleteAll()
        }
    }

    /**
     * 1.个人Fragment的菜单
     */
    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        super.onCreateOptionsMenu(menu, inflater)
        inflater.inflate(R.menu.personal_menu, menu)
    }

    override fun showResultSuccess(result: List<Student>?) {
        Log.d(Flag.TAG,"showResultSuccess result: ${result.toString()} , LV:${recyclerView} ")

        //将数据交给recycleView显示
        val adapter = CollectAdapter()
        if(null != result){
            adapter.allStudents = result;
        }
        recyclerView.adapter = adapter
    }

    //1.增、删、改的反馈,即做完之后重新刷新请求所有数据
    override fun showResult(result: Boolean) {
        if (result) p.requestQueryAll()
    }

    //1.创建Presenter对象
    override fun getPresenter(): CollectPresenter = CollectPresenterImpl(this)

    override fun createOK() {
        //1.查询所有
        p.requestQueryAll()
    }

    override fun recycle() {
        p.unAttachView()
    }

}

1.3 Adapter of RecycleView

/**
 * @author XiongJie
 * @version appVer
 * @Package com.gdc.kotlinproject.adapter
 * @file
 * @Description:
 * @date 2021-6-4 19:46
 * @since appVer
 */
class CollectAdapter : RecyclerView.Adapter<CollectAdapter.MyViewHolder>() {

    //接收数据库的数据
    var allStudents:List<Student> = ArrayList()

    /**
     * 内部类
     */
    inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var tvID: TextView = itemView.findViewById(R.id.tv_id)
        var tvName: TextView = itemView.findViewById(R.id.tv_name)
        var tvAge: TextView = itemView.findViewById(R.id.tv_age)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        //1.Item布局
        val layoutInflater:LayoutInflater = LayoutInflater.from(parent.context)
        val itemView:View = layoutInflater.inflate(R.layout.item_collect_list,parent,false)
        return MyViewHolder(itemView)
    }

    override fun getItemCount(): Int = allStudents.size

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        val student : Student = allStudents[position]
        holder.tvID.text = "${position + 1}"
        holder.tvName.text = student.name
        holder.tvAge.text = "${student.age}"

        // 点击Item的时候,可以跳转到  有道词典 查询
        holder.itemView.setOnClickListener {
            val uri: Uri = Uri.parse("https://m.youdao.com/dict?le=eng&q=" + holder.tvName.text)
            val intent: Intent = Intent(Intent.ACTION_VIEW)
            intent.data = uri;
            holder.itemView.context.startActivity(intent)
        }
    }
}

2.Presenter layer

class CollectPresenterImpl(var view : CollectView?):CollectPresenter,CollectPresenter.OnCollectListener,CollectPresenter.OnCollectionResponseListener  {

    //1.Model层
    private val model:CollectModel = CollectModelImpl()

    //1.插入
    //1.1*students是将可变参数取出来之后丢给Model层的可变参数
    override fun requestInsert(vararg students: Student) {
        model.requestInsert(this,*students)
    }

    //1.修改
    override fun requestUpdate(vararg students: Student) {
        model.requestUpdate(this,*students)
    }

    //1.删除
    override fun requestDelete(vararg students: Student) {
        model.requestDelete(this,*students)
    }

    //1.删除全部
    override fun requestDeleteAll() {
        model.requestDeleteAll(this)
    }

    //1.查询全部
    override fun requestQueryAll() {
        model.requestQueryAll(this)
    }

    override fun unAttachView() {
        view == null
    }

    //1.显示结果
    override fun showResultSuccess(result: List<Student> ?) {
        view?.showResultSuccess(result)
    }

    //1.显示增、删、改结果
    override fun showIUD(iudResult: Boolean) {
        view?.showResult(iudResult)
    }
}

3.Model layer

import android.util.Log
import com.gdc.kotlinproject.config.Flag
import com.gdc.kotlinproject.data_model.local.LocalRoomRequestManager
import com.gdc.kotlinproject.database.Student
import com.gdc.kotlinproject.modules.collect.interfaces.CollectModel
import com.gdc.kotlinproject.modules.collect.interfaces.CollectPresenter

/**
 * @author XiongJie
 * @version appVer
 * @Package com.gdc.kotlinproject.modules.collect
 * @file
 * @Description:Model实现层
 * @date 2021-6-4 20:08
 * @since appVer
 */
class CollectModelImpl : CollectModel{

    override fun requestInsert(
        listener: CollectPresenter.OnCollectListener,
        vararg studests: Student
    ) {
        LocalRoomRequestManager.getInstance().insertStudents(*studests)
        // TODO 伪代码:例如:这里还可以做很多的逻辑,等等,最终确保此操作没有问题,就返回true
        //  ......
        listener.showIUD(true)
    }

    override fun requestUpdate(
        listener: CollectPresenter.OnCollectListener,
        vararg studests: Student
    ) {
        LocalRoomRequestManager.getInstance().updateStudents(*studests)
        // TODO 伪代码:例如:这里还可以做很多的逻辑,等等,最终确保此操作没有问题,就返回true
        //  ......
        listener.showIUD(true)
    }

    override fun requestDelete(
        listener: CollectPresenter.OnCollectListener,
        vararg studests: Student
    ) {
        LocalRoomRequestManager.getInstance().deleteStudents(*studests)
        // TODO 伪代码:例如:这里还可以做很多的逻辑,等等,最终确保此操作没有问题,就返回true
        //  ......
        listener.showIUD(true)
    }

    override fun requestDeleteAll(listener: CollectPresenter.OnCollectListener) {
        LocalRoomRequestManager.getInstance().deleteAllStudent()
        // TODO 伪代码:例如:这里还可以做很多的逻辑,等等,最终确保此操作没有问题,就返回true
        //  ......
        listener.showIUD(true)
    }

    override fun requestQueryAll(listener: CollectPresenter.OnCollectionResponseListener) {
        val result = LocalRoomRequestManager.getInstance().queryAllStudent()
        Log.d(Flag.TAG, "requestQueryAll: result$result")
        listener.showResultSuccess(result)
    }
}

4. Database operation management

/**
 * @author XiongJie
 * @version appVer
 * @Package com.gdc.kotlinproject.data_model.local
 * @file
 * @Description:
 * 1.本地数据库相关操作管理
 * (1)负责Dao对象的创建
 * (2)负责Dao具体操作的执行
 * (3)实现ILocalRequest与IDatabaseRequest接口,是为了实现业务方法的扩展
 * @date 2021-6-4 20:28
 * @since appVer
 */
class LocalRoomRequestManager : ILocalRequest,IDatabaseRequest{

    //1.DAO对象
    var studentDao : StudentDao? = null

    //1.Java构造代码块
    init {
        //1.1获取数据库对象
        val studentDatabase:StudentDatabase? = StudentDatabase.getDatabase()

        studentDao = studentDatabase?.getStudentDao()
    }

    //1.本类单例
    companion object{
        var INSTANCE : LocalRoomRequestManager? = null

        fun getInstance() : LocalRoomRequestManager{
            if(null == INSTANCE){
                synchronized(LocalRoomRequestManager::class){
                    if(null == INSTANCE){
                        INSTANCE = LocalRoomRequestManager()
                    }
                }
            }
            //!!表示
            return INSTANCE!!
        }
    }

    override fun insertStudents(vararg students: Student) {
        studentDao?.insertStudents(*students)
    }

    override fun updateStudents(vararg students: Student) {
        studentDao?.updateStudents(*students)
    }

    override fun deleteStudents(vararg students: Student) {
        studentDao?.deleteStudents(*students)
    }

    override fun deleteAllStudent() {
        studentDao?.deleteAllStudent()
    }

    override fun queryAllStudent(): List<Student>? {
       return studentDao?.queryAllStudent()
    }

}

4.1 Local data extension interface

/**
 * @author XiongJie
 * @version appVer
 * @Package com.gdc.kotlinproject.data_model.local
 * @file
 * @Description:
 *
 * 1.本地数据业务操作扩展
 *
 * (1)xml数据操作
 *
 * (2)其他本地数据
 *
 * 2.为了扩展,这样写(在仓库里面的)
 *
 * 3.本地获取标准接口(在仓库里面) 也就是本地的数据读取(包括本地xml数据,等)
 *
 * 4.只为 LocalRoomRequestManager 服务
 *
 * @date 2021-6-4 20:27
 * @since appVer
 */
interface ILocalRequest {

}

4.2 Database extension interface

/**
 * @author XiongJie
 * @version appVer
 * @Package com.gdc.kotlinproject.data_model.local
 * @file
 * @Description:
 *
 * 1.数据库获取标准接口
 *
 * (1)即数据库的数据读取
 *
 * (2)只为 LocalRoomRequestManager 服务
 *
 * 2.这样写是为了扩展
 *
 * @date 2021-6-4 20:26
 * @since appVer
 */
interface IDatabaseRequest {

    fun insertStudents(vararg students: Student)

    fun updateStudents(vararg students: Student)

    fun deleteStudents(vararg students: Student)

    fun deleteAllStudent()

    fun queryAllStudent() : List<Student> ?

}

5. Reward and encouragement

Thank you for your careful reading, your encouragement is the inexhaustible motivation for my writing! ! !

5.1 WeChat Reward

Insert picture description here

5.2 Alipay rewards

5.1 WeChat Reward

Insert picture description here

5.2 Alipay rewards

Insert picture description here