This Fragment saving result when it detach in onStop() method and in onStart() read last query result and again display it.
フラグメントが停止したとき、またはアプリがプロセスから切り離されたときにクエリ結果を保存しようとしています。プロセスに戻ったときに、アプリは最後の検索クエリ結果を表示しますが、アプリはデフォルトのクエリ結果を表示します。事前に感謝し、英語で申し訳ありません。
コトリン
@AndroidEntryPoint
class GalleryFragment : Fragment(R.layout.fragment_gallery),
GalleryPhotoAdapter.OnClickItemListener {
private val galleryViewModel by viewModels<GalleryViewModel>()
lateinit var queryUpdate: String
lateinit var photoAdapter: GalleryPhotoAdapter
private lateinit var binding: FragmentGalleryBinding
@Inject
lateinit var lastPreference:LastPreference
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentGalleryBinding.bind(view)
// dataStore= context?.createDataStore(name = "SAVED_QUERY")!!
Log.d("GalleryFragment", "onViewCreated:context is $context")
photoAdapter = GalleryPhotoAdapter(this)
setupRecyclerView()
// updateQueryData("cats")
setHasOptionsMenu(true)
}
private fun updateQueryData(query: String) {
viewLifecycleOwner.lifecycleScope.launchWhenStarted {
galleryViewModel.getPhotos(query).collectLatest {
photoAdapter.submitData(it)
}
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.gallery_menu, menu)
val searchItem = menu.findItem(R.id.search_view)
val searchView = searchItem.actionView as SearchView
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
if (query != null) {
binding.recyclerView.scrollToPosition(0)
queryUpdate = query
updateQueryData(query)
searchView.clearFocus()
}
return true
}
override fun onQueryTextChange(newText: String?): Boolean {
return true
}
})
}
private fun setupRecyclerView() {
binding.apply {
recyclerView.apply {
setHasFixedSize(true)
itemAnimator = null
adapter = photoAdapter.withLoadStateHeaderAndFooter(
header = GalleryLoadStatesAdapter { photoAdapter.retry() },
footer = GalleryLoadStatesAdapter { photoAdapter.retry() }
)
}
}
photoAdapter.addLoadStateListener { loadStates ->
binding.apply {
progressBar.isVisible = loadStates.source.refresh is LoadState.Loading
recyclerView.isVisible = loadStates.source.refresh is LoadState.NotLoading
textViewError.isVisible = loadStates.source.refresh is LoadState.Error
buttonRetry.isVisible = loadStates.source.refresh is LoadState.Error
if (loadStates.source.refresh is LoadState.NotLoading &&
loadStates.append.endOfPaginationReached
&& photoAdapter.itemCount == 0
) {
recyclerView.isVisible = false
textViewEmpty.isVisible = true
} else {
textViewEmpty.isVisible = false
}
}
}
}
override fun onItemClick(photo: UnsplashPhoto) {
val action = GalleryFragmentDirections.actionGalleryFragmentToDetailFragment(photo)
findNavController().navigate(action)
}
override fun onStart() {
super.onStart()
viewLifecycleOwner.lifecycleScope.launchWhenStarted {
lastPreference.readLastQuery().collectLatest {
updateQueryData(it)
}
}
}
override fun onStop() {
super.onStop()
// Log.d("GalleryFragment", "onStop: $queryUpdate")
//saving Query
viewLifecycleOwner.lifecycleScope.launchWhenStarted {
lastPreference.saveLastQuery(queryUpdate)
}
}
}
このクラスでは、データストア設定を使用してデータを保存および読み取ります
コトリン
@Singleton
class LastPreference @Inject constructor(@ApplicationContext val context: Context) {
companion object {
val CURRENT_QUERY_KEY = preferencesKey<String>("current_query")
private const val DEFAULT_QUERY = "cats"
}
private val dataStore = context.createDataStore("user_preferences")
suspend fun saveLastQuery(query: String) {
dataStore.edit {
it[CURRENT_QUERY_KEY] = query
}
}
fun readLastQuery() = dataStore.data
.catch { e ->
Log.d("LastPreference", "readLastQuery: ${e.message} ")
}.map {
it[CURRENT_QUERY_KEY] ?: DEFAULT_QUERY
}
}