gpt4 book ai didi

android - 回收站 View 未正确更新

转载 作者:行者123 更新时间:2023-12-02 12:25:04 28 4
gpt4 key购买 nike

我已经多次问过这个类似的问题,我花了 2 周多的时间才试图找出解决方案。是的,我知道有多个类似的问题,但我问的原因是因为堆栈上流的解决方案都不起作用。我是 Android 开发的初学者,因此我问你请帮我解决这个问题。我几乎要放弃我的项目了。

应用如何运作

应用程序有两个 Activity 。主要 Activity 用于使用从 SQ Lite DB 加载的回收器 View 以卡片 View 的形式显示数据。用户可以单击卡片,单击该卡片将启动新 Activity (引用 Activity )。单击卡片的数据在第二个 Activity 中加载。用户可以在这里执行UPDATEDELETE 功能。

问题

问题是我必须重新启动我的应用程序才能看到注释中的更改。例如,如果我在第二个 Activity 中创建了一个笔记并返回到主 Activity ,则该CREATED 笔记在应用程序重新启动之前是可见的。更新或删除笔记时也是如此。更改仅在应用重新启动时发生。

到目前为止我尝试了什么......

  • 在 MAIN Activity 的 onRestart() 中调用了 notifyDataSetChanged()。

  • 调用了在 onRestart() 中首先加载回收器 View 项的整个加载

  • 尝试用新数据更新适配器

----- 代码 -----

主要 Activity

class MainActivity : AppCompatActivity() {

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

var updatedTitle: String? = null
var updatedText: String? = null

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 onRestart() {
super.onRestart()

if(isUpdated)
{
recyclerViewID.recycledViewPool.clear()
var test = listItems!![adapPos]
test.noteTitle = updatedTitle
test.noteText = updatedText
listItems!!.set(adapPos, test)
adapter!!.notifyItemChanged(adapPos)

isUpdated = false
}
}


override fun onStart() {
super.onStart()

if(isReturning)
{
adapter!!.updateResults(this.listItems!!)
adapter!!.notifyDataSetChanged()
}

adapter = PediaAdapter(this, listItems!!)
layoutManager = LinearLayoutManager(this)

recyclerViewID.adapter = adapter
recyclerViewID.layoutManager = layoutManager


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(dbHandler.totalNotes() == 0) {
recyclerViewID.visibility = View.GONE
}
else{
recyclerViewID.visibility = View.VISIBLE
showWhenEmptyID.visibility = View.GONE
}
recyclerViewID.hasFixedSize()
}





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")

updatedTitle = data!!.extras.getString("updatedTitle")
updatedText = data!!.extras.getString("updatedText")

isReturning = data.extras!!.getBoolean("returningBack")
// isUpdated = data.extras!!.getBoolean("isUpdated")
}
}


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()

}
}

引用 Activity

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 dataCreate = this.intent
dataCreate.putExtra("isUpdated", true)
dataCreate.putExtra("updatedTitle", title)
dataCreate.putExtra("updatedText",text)
dataCreate.putExtra("returningBack", true)
setResult(Activity.RESULT_OK, dataCreate)


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)

var dataCreate = this.intent
dataCreate.putExtra("isCreated", true)
dataCreate.putExtra("returningBack", 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)
}

适配器

class PediaAdapter(private val context: Context,
private var 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)
}

}

fun updateResults(items: ArrayList<UserNotes>)
{
this.noteslist = items
}

是的,我知道很难通过某人的代码。我已经尝试过多次修复它,整天坐着试图弄清楚它,但仍然没有运气。我请求你帮我解决这个问题。我不在乎你是否在 Java 中这样做,我只需要一种修复它的方法。

最佳答案

像这样在 AndroidManifest.xml 文件中声明您的 MainActivity。

android:launchMode="singleTask"

在完成“ReferenceActivity”(即调用 finish())之前,对您的“MainActivity”进行 Intent 调用。此外,覆盖“MainActivity”中的“onNewIntent()”方法。

@Override
protected void onNewIntent(Intent intent)

在“onNewIntent()”方法中,再次加载数据,就像您在“onStart()”和“onRestart()”中所做的那样。

说明,我们正在做的是在 Activity Stack 中添加对“MainActivity”的单个引用,因此每当对“MainActivity”进行 Intent 调用而不是创建多个引用时,它只会创建一个引用并每次调用 newIntentMethod .

希望这能解决您的问题。

关于android - 回收站 View 未正确更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52028398/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com