BroadcastReciever复制项目

时间:2018-11-07 12:15:59

标签: android kotlin broadcastreceiver

您好,我有一个应用程序,我在其中使用BroadcastReciever通知recyclerview中的更改。现在的问题是,只要我的数据持续存在,应用程序处于活动状态时,数据就会重复,但是如果我重新运行该应用程序,下面显示的数据是我的代码正常,我不知道我在做什么错。 >

我正在使用领域来保留我的数据

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        GroupService.getGroups {success ->
            if (success) {
                LocalBroadcastManager.getInstance(this).registerReceiver(userDataChangeReceiver, IntentFilter(BROADCAST_USER_DATA_CHANGE))
            }
        }

//        Log.d("GROUP", "GROOUUPPP ${GroupService.groups.count()}")

        setupAdapters()
        fabClicked()

    }

    private fun fabClicked () {
        fab.setOnClickListener {

        Log.d("GROUP", "fab pressed added")
        val builder = AlertDialog.Builder(this)
        val dialogView = layoutInflater.inflate(R.layout.add_group_dialog, null)

        builder.setView(dialogView)
                .setPositiveButton("Add") { _, _ ->
                    // perform onclick logic
                    val titleTxtFld = dialogView.findViewById<EditText>(R.id.addGroupTitle)

                    val groupName = titleTxtFld.text.toString()

                    if (groupName.isNotEmpty()) {

//                        groupAdapter.notifyDataSetChanged()
                        GroupService.addGroup(groupName)
                        { success ->
                            if (success) {
                                val userDataChanged = Intent(BROADCAST_USER_DATA_CHANGE)
                                LocalBroadcastManager.getInstance(this).sendBroadcast(userDataChanged)

                            }
                        }
                    }
                    Log.d("GROUP", "group $groupName added")

                }

                .setNegativeButton("Cancel") { dialogInterface, i ->
                    // close dialog
                }
                .show()

        }
    }

    private val userDataChangeReceiver = object : BroadcastReceiver() {
        override fun onReceive(contect: Context, intent: Intent?) {

            GroupService.getGroups { success ->
                groupAdapter.notifyDataSetChanged()
                if (success) {
                    if (GroupService.groups.count() > 0) {
                        groupAdapter.notifyDataSetChanged()

                    }
                }
            }
        }
    } 

如果我能指出我的错误,我会很高兴。预先感谢

0 个答案:

没有答案