如何在onRestart()上重绘RecyclerView的卡片视图?

时间:2018-08-20 08:16:41

标签: android sqlite android-recyclerview kotlin cardview

我做了一个做笔记的应用程序,它可以执行基本的笔记动作(CRUD)。问题是,每当用户从第二个活动中删除/创建或更新便笺时,主要活动(持有回收者视图)都不会反映出任何更改。

仅在重新启动应用程序,屏幕方向更改以及关闭和再次打开手机屏幕时反映更改。我已经尝试了stackoverflow的所有其他解决方案,但没有任何效果。我仍然必须重新启动应用程序才能看到更改。我仍然是初学者,所以我不知道任何实时数据,RxJava或任何其他高级体系结构

问题是,从第二次活动返回后如何在回收者视图中重置卡片视图?

主要活动

class MainActivity : AppCompatActivity() {

var dbHandler: PediaDatabase? = null
var adapter: PediaAdapter? = null
var layoutManager: RecyclerView.LayoutManager? = null
var list: ArrayList<UserNotes>? = ArrayList()
var listItems: ArrayList<UserNotes>? = ArrayList()
var myPrefs: SharedPreferences? = null
var first_run: Boolean = true
var isCreated: Boolean = false
var isUpdated: Boolean = false
var isDeleted: Boolean = false

val PREFS_NAME: String = "MYPREFS"
val REQUEST_CODE: Int = 1



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

     showOneTimeMessage()
     invalidateOptionsMenu()

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
    {
        window.navigationBarColor = Color.BLACK
    }

}

override fun onResume() {
    super.onResume()



    if(adapter != null)
    {
        recyclerViewID.recycledViewPool.clear()
        recyclerViewID.invalidate()
    }


    Toast.makeText(this, "ONSTART", Toast.LENGTH_SHORT).show()
    dbHandler = PediaDatabase(this)
    adapter = PediaAdapter(this, listItems!!)
    layoutManager = LinearLayoutManager(this)

    recyclerViewID.adapter = adapter
    recyclerViewID.layoutManager = layoutManager


    list = dbHandler!!.readAllNotes()
    //listItems = ArrayList()

    for(reader in list!!.iterator())
    {
        var note = UserNotes()

        note.noteTitle = reader.noteTitle
        note.noteText = reader.noteText
        note.noteID = reader.noteID
        note.noteDate = reader.noteDate

        listItems!!.add(note)
    }

    adapter!!.notifyDataSetChanged()


    if(dbHandler!!.totalNotes() == 0) {
        recyclerViewID.visibility = View.GONE
    }
    else{
        recyclerViewID.visibility = View.VISIBLE
        showWhenEmptyID.visibility = View.GONE
    }
    recyclerViewID.hasFixedSize()
}


override fun onRestart() {
    super.onRestart()


    list!!.clear()

    list = dbHandler!!.readAllNotes()

    for(reader in list!!.iterator())
    {
        var note = UserNotes()

        note.noteTitle = reader.noteTitle
        note.noteText = reader.noteText
        note.noteID = reader.noteID
        note.noteDate = reader.noteDate

        listItems!!.add(note)
        adapter!!.notifyDataSetChanged()
    }





    if(isCreated)
    {
        val newIndex: Int = listItems!!.size + 1
        listItems!!.add(newIndex,existingNote)
        adapter!!.notifyItemInserted(newIndex)

    }
}


override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    if(requestCode == REQUEST_CODE)
        if(resultCode == Activity.RESULT_OK)
        {
            isCreated = data?.extras!!.getBoolean("isCreated")
        }
}


override fun onCreateOptionsMenu(menu: Menu?): Boolean {
    menuInflater.inflate(R.menu.top_menu, menu)

    val item = menu!!.findItem(R.id.delete_note_menu)
    item.setVisible(false)
    return true
}


override fun onOptionsItemSelected(item: MenuItem?): Boolean {

    if(item!!.itemId == R.id.add_note_menu){

        isNewNote = true
        startActivity(Intent(this, ReferenceActivity::class.java))
    }

    if(item!!.itemId == R.id.delete_note_menu)
    {

        Toast.makeText(this,"DELETED", Toast.LENGTH_SHORT).show()
    }

    return super.onOptionsItemSelected(item)
}

private fun showOneTimeMessage()
{
    var data: SharedPreferences = getSharedPreferences(PREFS_NAME, 0)
    if(data.contains("isShown"))
    {
        first_run = data.getBoolean("isShown", true)
    }


    Log.d("FIRST_RUN", first_run.toString())

    if(first_run)
    {
        val oneTimeMsg = SweetAlertDialog(this)
        oneTimeMsg.setTitleText("Hey there!")
        oneTimeMsg.setContentText("Thank you for downloading! Please don`t forget to rate our app :)").show()

        oneTimeMsg.setConfirmClickListener(object : SweetAlertDialog.OnSweetClickListener
        {

            override fun onClick(sweetAlertDialog: SweetAlertDialog?)
            {
                oneTimeMsg.dismissWithAnimation()
            }
        }).show()


        myPrefs = getSharedPreferences(PREFS_NAME, 0)
        var editor: SharedPreferences.Editor = (myPrefs as SharedPreferences).edit()
        editor.putBoolean("isShown", false)
        editor.commit()

    }
}

适配器类

class PediaAdapter(private val context: Context,
               private val noteslist: ArrayList<UserNotes>): RecyclerView.Adapter<PediaAdapter.ViewHolder>()

{

override fun onCreateViewHolder(p0: ViewGroup, p1: Int): ViewHolder
{
    val view = LayoutInflater.from(context).inflate(R.layout.list_row,p0,false)

    return ViewHolder(view, noteslist)
}

override fun getItemCount(): Int
{
    return noteslist.size
}

override fun onBindViewHolder(p0: ViewHolder, p1: Int)
{
    p0.bindItems(noteslist[p1])
}

inner class ViewHolder(itemView: View, list: ArrayList<UserNotes>): RecyclerView.ViewHolder(itemView), View.OnClickListener
{
    private var noteTitle = itemView.findViewById(R.id.listTitleID) as TextView
    private var noteText = itemView.findViewById(R.id.listTextID) as TextView

    var mList = list


    init
    {
        itemView.setOnClickListener(this)
    }

    fun bindItems(note: UserNotes)
    {
        //var id = note.noteID
        noteTitle.text = note.noteTitle
        noteText.text = note.noteText
    }

    override fun onClick(v: View?)
    {

        var mPosition: Int =  adapterPosition //For forwarding position to ref activity
        var note = mList[mPosition]
        adapPos = adapterPosition


        var cardID = Intent(itemView.context, ReferenceActivity::class.java)
        cardID.putExtra("cardPosition", mPosition)
        cardID.putExtra("cardID", note.noteID) //TODO THIS IS FETCHING NOTE_ID VALUES FROM DB

        Toast.makeText(itemView.context, "card id = " + note.noteID, Toast.LENGTH_SHORT).show()

        itemView.context.startActivity(cardID)
    }

}

参考活动(第二次)

class ReferenceActivity : AppCompatActivity() {

var dbHandler: PediaDatabase? = null
var note = UserNotes()

var noteExisted: Boolean = false
var cardAdapterPos: Int? = null

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

    getSupportActionBar()!!.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM)
     getSupportActionBar()!!.setCustomView(R.layout.custom_toolbar)
      val dateTxtView = findViewById<View>(resources.getIdentifier("action_bar_title", "id", packageName)) as TextView


    overridePendingTransition(R.anim.slide_in, R.anim.slide_out)

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        window.navigationBarColor = Color.BLACK


    dbHandler = PediaDatabase(this)
    val data = intent
        if(isNewNote != true/*isNewNote.extras.getBoolean("isNewNote") != true*/)
        {
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)

            if(data != null)
            {
                noteExisted = true

                this.cardAdapterPos = data.extras.getInt("cardPosition")
                cardID = data.extras.getInt("cardID")


                existingNote = dbHandler!!.readNote(cardID)

                refTitleID.setText(existingNote.noteTitle, TextView.BufferType.EDITABLE)
                refTextID.setText(existingNote.noteText, TextView.BufferType.EDITABLE)
                dateTxtView.text = existingNote.noteDate.toString()
            }
        }else{
            dateTxtView.text = "New note"
        }
}

override fun onStop() {
    super.onStop()


    var title: String = refTitleID.text.toString().trim()
    var text: String = refTextID.text.toString().trim()

    if(existingNote.noteText == text && existingNote.noteTitle == title)
        finish()

    if(noteExisted)
    {
        if(TextUtils.isEmpty(title))
            title = "No title"


        existingNote.noteTitle = title
        existingNote.noteText = text
        existingNote.noteDate = System.currentTimeMillis().toString() //TODO TRY THIS


        dbHandler!!.updateNote(existingNote)

        var sharedPrefs = getSharedPreferences(PREFS_SHARE, Context.MODE_PRIVATE)
        val share_editor: SharedPreferences.Editor = (sharedPrefs as SharedPreferences).edit()
        share_editor.putBoolean("update", true).commit()


        finish()
    }
    else
    {
        if(TextUtils.isEmpty(title) && TextUtils.isEmpty(text))
        {
            finish()
        }
        else
        {
            if(TextUtils.isEmpty(title))
                title = "No title"

            note.noteTitle = title
            note.noteText = text
            note.noteDate = System.currentTimeMillis().toString()
           // note.noteID =

            dbHandler!!.createNote(note)

            val dataCreate = this.intent
            dataCreate.putExtra("isCreated", true)
            setResult(Activity.RESULT_OK, dataCreate)

            finish()
        }
    }
}


override fun onCreateOptionsMenu(menu: Menu?): Boolean {

    menuInflater.inflate(R.menu.top_menu, menu)
    val addItem: MenuItem = menu!!.findItem(R.id.add_note_menu)
    val delItem:MenuItem = menu.findItem(R.id.delete_note_menu)


    addItem.setVisible(false)
    delItem.setVisible(false)

    if(noteExisted)
        delItem.setVisible(true)

    return true
}

override fun onOptionsItemSelected(item: MenuItem?): Boolean {

    if(item!!.itemId == R.id.delete_note_menu)
    {
        val dialogMsg = SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
        dialogMsg.setTitleText("Are you sure?")
        dialogMsg.setContentText("You won`t be able to recover this note!")
        dialogMsg.setConfirmText("Yes, delete it!")

        dialogMsg.setConfirmClickListener(object: SweetAlertDialog.OnSweetClickListener {

            override fun onClick(sweetAlertDialog: SweetAlertDialog?) {
                dialogMsg.dismissWithAnimation()


                dbHandler!!.deleteNote(cardID)


                val successMsg = SweetAlertDialog(sweetAlertDialog!!.context, SweetAlertDialog.SUCCESS_TYPE)
                successMsg.setTitleText("Note deleted!")
                successMsg.setContentText("So long,note").show()
                successMsg.setCancelable(false)

                //TODO Disable 'OK' button on successMsg dialogbox

                Handler().postDelayed({
                    successMsg.dismissWithAnimation()
                    finish()
                }, 1200)

            }
        }).show()

    }
    return super.onOptionsItemSelected(item)
}

1 个答案:

答案 0 :(得分:0)

从第二个活动返回时,您可以拨打电话

adapter.notifyDataSetChanged();

为了告诉RV的适配器重新创建所有viewHolders并重新绑定视图。

但是,最好是您知道被删除/更新的项目的确切索引。这样,您可以致电:

adapter.notifyItemRemoved(position)

告诉适配器删除该项目,或者:

adapter.notifyItemChanged(position)

为了告诉适配器重新绘制(调用onBindViewHolder)特定项。

编辑:我看到您已经在调用这些方法,但是您从未更新适配器持有的列表!您正在活动中而不是适配器中更新列表。因此,您应该做的是将这样的方法添加到适配器中:

fun updateResults(items: List<UserNotes>) {
    noteslist = items
}

,然后将“ noteslist”的val更改为var。用新列表调用“ updateResults”后,调用

adapter.notifyDataSetChanged();