gpt4 book ai didi

android - SavedStateHandle 返回空值

转载 作者:行者123 更新时间:2023-12-03 14:54:24 26 4
gpt4 key购买 nike

我有一个 ActionBar打开 CategoryFragment 的菜单图标.该 fragment 采用 category对象 SafeArgs从另一个 fragment 传递的参数。在 CategoryFragment ,我存储category的名称和 id 进入 fragment 的共享 ViewModelSavedStateHandle值(value)观。我已经设置它,以便 fragment 使用存储的 SavedStateHandle需要时为类别名称和 id 设置值。例如,第一次使用 CategoryFragment使用从发送 fragment 传递的类别对象,但随后创建 CategoryFrgament将使用 SavedStateHandle值(value)观。

问题是,如果在第一次打开 CategoriesFragment然后通过按下手机的物理后退按钮或从导航栏中手机的最近按钮终止应用程序退出应用程序,现在打开 CategoryFragment直接按ActionBar 菜单图标显示一个空白屏幕。这是因为从 SavedStateHandle 返回的值为空。我怎样才能解决这个问题?

分类 fragment

class CategoryFragment : Fragment(), SearchView.OnQueryTextListener {

lateinit var navController: NavController
private var adapter: TasksRecyclerAdapter? = null
private val viewModel: CategoryTasksViewModel by activityViewModels()
private var fromCategoriesFragment: Boolean = false

override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_category, container, false)
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)

navController = Navigation.findNavController(view)

observerSetup()
recyclerSetup()

var searchView = category_tasks_searchview
searchView.setOnQueryTextListener(this)

fab_new_task.setOnClickListener {
navController.navigate(R.id.action_categoryFragment_to_newTaskDialogFragment)
}

showTasks()
}

private fun showTasks() {

if(fromCategoriesFragment){

PomoPlayObservablesSingleton.fromCategoriesFragment.onNext(false)

if (!arguments?.isEmpty!!) {

var args = CategoryFragmentArgs.fromBundle(arguments!!)
category_title.text = args.category?.name

var category = args.category
viewModel.setPomoCategoryName(category.name)
viewModel.setCategoryId(category.id)
viewModel.searchTasksByCategoryId(category.id)

}

}
else{
category_title.text = viewModel.getPomoCategoryName()
viewModel.searchTasksByCategoryId(viewModel.getCategoryId())

Log.i("CategoryFrag-CatName", viewModel.getPomoCategoryName().toString())
Log.i("CategoryFrag-CatId", viewModel.getCategoryId().toString())
}
}

private fun observerSetup() {

viewModel.getSearchTasksByCategoryIdResults().observe(this,androidx.lifecycle.Observer { tasks ->

if(tasks.isNotEmpty()){

adapter?.setTasksList(tasks.sortedBy { task -> task.name?.toLowerCase() })
task_not_found_bubble.visibility = View.GONE
task_not_found_text.visibility = View.GONE
}
else{
task_not_found_bubble.visibility = View.VISIBLE
task_not_found_text.visibility = View.VISIBLE
}
})

PomoPlayObservablesSingleton.fromCategoriesFragment.subscribe {value -> fromCategoriesFragment = value}

}

private fun recyclerSetup() {
adapter = context?.let { TasksRecyclerAdapter(it) }
tasks_list?.layoutManager = LinearLayoutManager(context)
tasks_list?.adapter = adapter
}

override fun onQueryTextSubmit(query: String?): Boolean {

Log.i("Lifecycle-CatFragment", "onQueryTextSubmit() called")

var q = query?.toLowerCase()?.trim()?.replace("\\s+".toRegex(), " ")
setLastSearchQuery(q.toString())

viewModel.searchTasksByName(viewModel.getLastSearchQuery().toString())

return false
}

private fun setLastSearchQuery(lastSearchQuery: String) {
viewModel.setLastSearchQuery(lastSearchQuery)
}
}

CategoryTasksViewModel
class CategoryTasksViewModel(application: Application, state: SavedStateHandle) : AndroidViewModel(application) {

private val repository: PomoPlayRepository = PomoPlayRepository(application)
private val allCategories: LiveData<List<Category>>?
private val allPomoTasks: LiveData<List<PomoTask>>?
private val searchCategoriesByNameResults: MutableLiveData<List<Category>>
private val searchCategoryByIdResults: MutableLiveData<Category>
private val searchTasksByIdResults: MutableLiveData<PomoTask>
private val searchTasksByNameResults: MutableLiveData<List<PomoTask>>
private val searchTasksByCategoryIdResults: MutableLiveData<List<PomoTask>>

private val savedStateHandle = state

companion object{

private const val LAST_SEARCH_QUERY = "lastSearchQuery"

}

init {
allCategories = repository.allCategories
allPomoTasks = repository.allPomoTasks
searchTasksByIdResults = repository.searchTasksByIdResults
searchTasksByNameResults = repository.searchTasksByNameResults
searchTasksByCategoryIdResults = repository.searchTasksByCategoryIdResults
searchCategoryByIdResults = repository.searchCategoriesByIdResults
searchCategoriesByNameResults = repository.searchCategoriesByNameResults
}

fun setLastSearchQuery(lastSearchName: String){
savedStateHandle.set(LAST_SEARCH_QUERY, lastSearchName)
}

fun getLastSearchQuery(): String?{
return savedStateHandle.get<String>(LAST_SEARCH_QUERY)
}

fun setPomoCategoryName(name: String?){
savedStateHandle.set("categoryName", name)
}

fun getPomoCategoryName(): String?{
return savedStateHandle.get<String>("categoryName")
}

fun setCategoryId(id: Int){
savedStateHandle.set("categoryId", id)
}

fun getCategoryId(): Int?{
return savedStateHandle.get<Int>("categoryId")
}

fun insertTask(pomoTask: PomoTask?) {
repository.insertTask(pomoTask)
}

fun deleteTask(pomoTask: PomoTask) {
repository.deleteTask(pomoTask)
}

fun updateTask(pomoTask: PomoTask) {
repository.updateTask(pomoTask)
}


fun searchTasksByName(name: String) {
repository.searchTasksByName(name)
}


fun searchTasksById(pomoTaskId: Int){
repository.searchTasksById(pomoTaskId)
}

fun searchTasksByCategoryId(categoryId: Int?){
repository.searchTasksByCategoryId(categoryId)
}

fun getAllPomoTasks() : LiveData<List<PomoTask>>? {
return allPomoTasks
}

fun getSearchTasksbyNameResults() : MutableLiveData<List<PomoTask>> {
return searchTasksByNameResults
}

fun getSearchTasksByIdResults() : MutableLiveData<PomoTask> {
return searchTasksByIdResults
}

fun getSearchTasksByCategoryIdResults() : MutableLiveData<List<PomoTask>> {
return searchTasksByCategoryIdResults
}

}

最佳答案

SavedStateHandle 不是设计用来做的,你期望它做的事情:它......

... is a key-value map that will let you write and retrieve objectsto and from the saved state. These values will persist after theprocess is killed by the system and remain available via the sameobject.


被系统杀死 ,而不是如果用户故意关闭应用程序甚至破坏(“永久导航”)作为其范围的 fragment/Activity 。请参阅 Saving UI State - User-initiated UI state dismissal 上的文档:

The user's assumption in these complete dismissal cases is that theyhave permanently navigated away from the activity, and if they re-openthe activity they expect the activity to start from a clean state. Theunderlying system behavior for these dismissal scenarios matches theuser expectation - the activity instance will get destroyed andremoved from memory, along with any state stored in it and any savedinstance state record associated with the activity.


也许将您希望在您的场景中幸存下来的信息保存在 SharedPreferences 中.

关于android - SavedStateHandle 返回空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60066753/

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