Summary doesn't persists on dynamically load data in ListPreference - android

In my SettingActivity I'm loading some data to be shown in ListPreference from Room, once the items are selected all works correctly, the value is saved to `SharedPreferences and the summary is shown correctly, but once I return to SettingsActivity the summary value is reset to null.
Here is what is happening:
My code is pretty simple, onViewCreated() I start observing LiveData to be shown in ListPreference and then I set the values for entries and entryValues
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.shops.observe(viewLifecycleOwner) {
setShopsPreferences(it)
}
}
private fun setShopsPreferences(shops: List<Shop>) {
val shopsPreference = preferenceManager.findPreference<ListPreference>("defaultShop")
if (shops.isEmpty()) {
shopsPreference?.isEnabled = false
return
} else {
shopsPreference?.isEnabled = true
}
val entries: ArrayList<String> = ArrayList()
val entryValues: ArrayList<String> = ArrayList()
shops.forEach {
entries.add(it.description)
entryValues.add(it.id)
}
shopsPreference?.entryValues = entryValues.toArray(arrayOfNulls<CharSequence>(entryValues.size))
shopsPreference?.entries = entries.toArray(arrayOfNulls<CharSequence>(entries.size))
}
ViewModel:
#HiltViewModel
class ShopsViewModel #Inject constructor(repository: ShopsRepository) : ViewModel() {
private val _shops = MutableLiveData<List<Shop>>()
val shops: LiveData<List<Shop>> = _shops
init {
repository.getAllShops().observeForever {
_shops.value = it
}
}
}
Repository:
fun getAllShops(): LiveData<List<Shop>> {
return shops.select()
}
DAO:
#Dao
interface ShopsDAO {
#Query("SELECT * FROM shops")
fun select(): LiveData<List<Shop>>
}

You are populating list entries dynamically after the preference hierarchy is already created by inflating the xml. But during that time there was no entry, hence the value was null. The data was then retrieved asynchronously but the change will not be reflected. So you have to set the summary manually.
Another approach I'm not sure about is to call recreate on the activity after populating the data inside the observer listener.

To resolve the issue with dynamic data in a ListPreference I've made some changes to my code, first of call in onCreatePreferences() I've added a preference listener to my ListPreference like this:
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.root_preferences, rootKey)
val shopsPreference = preferenceManager.findPreference<ListPreference>("defaultShop")
shopsPreference?.setOnPreferenceChangeListener { preference, newValue ->
val description = viewModel.shops.value?.find { it.id == newValue }
preference.summary = description?.description
true
}
}
So in that way on each new selection, I'm looking for the matching value for that preference in my ViewModel and getting the description for it which then is set as the summary.
While to set the summary every time the list has been changed or the SettingsActivity is opened I've added the following code to my setShopsPreferences() function:
private fun setShopsPreferences(shops: List<Shop>?) {
if (shops == null) {
return
}
val shopsPreference = preferenceManager.findPreference<ListPreference>("defaultShop")
// The preference is enabled only if there are shows inside the list
shopsPreference?.isEnabled = shops.isNotEmpty()
// Getting the defaultShop preference value, which will be used to find the actual shop description
val defaultShop = sharedPreferences.getString("defaultShop", "0")
defaultShop?.let { shopId ->
// Setting the summary based on defaultShop saved preference
shopsPreference?.summary = shops.find { it.id == shopId }?.description
}
val entries: ArrayList<String> = ArrayList()
val entryValues: ArrayList<String> = ArrayList()
shops.forEach {
entries.add(it.description)
entryValues.add(it.id)
}
shopsPreference?.entryValues =
entryValues.toArray(arrayOfNulls<CharSequence>(entryValues.size))
shopsPreference?.entries = entries.toArray(arrayOfNulls<CharSequence>(entries.size))
}

Related

Jetpack compose lazy column not recomposing with list

I have a list which is stored inside a Viewmodel via Stateflow.
class FirstSettingViewModel : ViewModel() {
private val _mRoomList = MutableStateFlow<List<InitRoom>>(mutableListOf())
val mRoomList: StateFlow<List<InitRoom>> = _mRoomList
...
I observe the flow via collectAsState(). The LazyColumn consists of Boxes which can be clicked.
val roomList = mViewModel.mRoomList.collectAsState()
Dialog {
...
LazyColumn(...) {
items(roomList.value, key = { room -> room.room_seq}) { room ->
Box(Modifier.clickable {
**mViewModel.selectItem(room)**
}) {...}
}
}
}
When a click event occurs, the viewModel changes the 'isSelected' value via a copied list like this.
fun selectItem(room: InitRoom) = viewModelScope.launch(Dispatchers.IO) {
try {
val cpy = mutableListOf<InitRoom>()
mRoomList.value.forEach {
cpy.add(it.copy())
}
cpy.forEach {
it.isSelected = it.room_seq == room.room_seq
}
_mRoomList.emit(cpy)
} catch (e: Exception) {
ErrorController.showError(e)
}
}
When in an xml based view and a ListAdapter, this code will work well, but in the above compose code, it doesn't seem to recompose the LazyColumn at all. What can I do to re-compose the LazyColumn?
Use a SnapshotStateList instead of an ordinary List
change this,
private val _mRoomList = MutableStateFlow<List<InitRoom>>(mutableListOf())
val mRoomList: StateFlow<List<InitRoom>> = _mRoomList
to this
private val _mRoomList = MutableStateFlow<SnapshotStateList<InitRoom>>(mutableStateListOf())
val mRoomList: StateFlow<SnapshotStateList<InitRoom>> = _mRoomList

mutableStateListOf change not reflecting in UI - Jetpack Compose

in my ViewModel:
private val _itemList = mutableStateListOf<Post>()
val itemList: List<Post> = _itemList
fun likePost(newPost: Post){
val index = _itemList.indexOf(newPost)
_itemList[index] = _itemList[index].copy(isLiked = true)
}
Here my Post data class:
data class Post(
val id: Int,
val name: String,
val isLiked: Boolean = false,
)
And here my Composable:
val postList = viewModel.itemList
LazyRow(content = {
items(postList.size) { i ->
val postItem = postList[i]
PostItem(
name = postItem.name,
isLiked = postItem.isLiked,
likePost = { viewModel.likePost(postItem)}
)
}
})
The change does not update in the UI instantly, I first have to scroll the updated item out of the screen so it recomposes or switch to another Screen and go back to see the change.
For some reason it doesn't like updating, it will add and delete and update instantly. You have to do it this way when updating for our to update the state.
fun likePost(newPost: Post){
val index = _itemList.indexOf(newPost)
_itemList[index] = _itemList[index].copy()
_itemList[index].isLiked = true
}
You are returning a List<> effectively and not MutableStateList from your ViewModel.
If you want the list to not be mutable from the view, I happen to use MutableStateFlow<List<>> and return StateFlow<List<>>. You could also just convert it to a list in your composable.
Edit:
//backing cached list, or could be data source like database
private val deviceList = mutableListOf<Device>()
private val _deviceListState = MutableStateFlow<List<Device>>(emptyList())
val deviceListState: StateFlow<List<BluetoothDevice>> = _deviceListState
//manipulate and publish
fun doSomething() {
_deviceListState.value = deviceList.filter ...
}
In your UI
val deviceListState = viewModel.deviceListState.collectAsState().value

Problem Implement Update UI with LiveData, Retrofit, Coroutine on Recyclerview : adapter Recyclerview not update

I'm newbie use Kotlin on my dev apps android,
and now, I on step learn to implement Update UI with LiveData, Retrofit, Coroutine on Recyclerview. The My Apps:
MainActivity > MainFragment with 3 Tab fragment > HomeFragment, DashboardFragment, and SettingsFragment
I call function to get data from server on onCreateView HomeFragment, and observe this with show shimmer data on my Recylerview when is loading, try update RecyclerView when success, and show view Failed Load -button refresh when error.
The problem is:
Adapter Recyclerview not Update when success get Data from Server. Adapter still show shimmer data
With case error (no Internet), i show view Failed Load, with button refresh. Tap to refresh, i re-call function to get data server, but fuction not work correct. Recyclerview show last data, not show Failed Load again.
Bellow my code
HomeFragment
private var _binding: FragmentHomeBinding? = null
private val binding get() = _binding!!
private lateinit var adapterNews: NewsAdapter
private var shimmerNews: Boolean = false
private var itemsDataNews = ArrayList<NewsModel>()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
_binding = FragmentHomeBinding.inflate(inflater, container, false)
......
newsViewModel = ViewModelProvider(requireActivity()).get(NewsViewModel::class.java)
//news
binding.frameNews.rvNews.setHasFixedSize(true)
binding.frameNews.rvNews.layoutManager = llmh
adapterNews = NewsAdapter(itemsDataNews, shimmerNews)
binding.frameNews.rvNews.adapter = adapterNews
// Observe
//get News
newsViewModel.refresh()
newsViewModel.newsList.observe(
viewLifecycleOwner,
androidx.lifecycle.Observer { newsList ->
newsList?.let {
binding.frameNews.rvNews.visibility = View.VISIBLE
binding.frameNews.rvNews.isNestedScrollingEnabled = true
binding.frameNews.itemNewsLayoutFailed.visibility = View.GONE
if (it.size == 0)
binding.frameNews.root.visibility = View.GONE
else
getDataNews(it)
}
})
newsViewModel.loading.observe(viewLifecycleOwner) { isLoading ->
isLoading?.let {
binding.frameNews.rvNews.visibility = View.VISIBLE
binding.frameNews.rvNews.isNestedScrollingEnabled = false
binding.frameNews.itemNewsLayoutFailed.visibility = View.GONE
getDataNewsShimmer()
}
}
newsViewModel.loadError.observe(viewLifecycleOwner) { isError ->
isError?.let {
binding.frameNews.rvNews.visibility = View.INVISIBLE
binding.frameNews.itemNewsLayoutFailed.visibility = View.VISIBLE
binding.frameNews.btnNewsFailed.setOnClickListener {
newsViewModel.refresh()
}
}
}
....
return binding.root
}
#SuppressLint("NotifyDataSetChanged")
private fun getDataNewsShimmer() {
shimmerNews = true
itemsDataNews.clear()
itemsDataNews.addAll(NewsData.itemsShimmer)
adapterNews.notifyDataSetChanged()
}
#SuppressLint("NotifyDataSetChanged")
private fun getDataNews(list: List<NewsModel>) {
Toast.makeText(requireContext(), list.size.toString(), Toast.LENGTH_SHORT).show()
shimmerNews = false
itemsDataNews.clear()
itemsDataNews.addAll(list)
adapterNews.notifyDataSetChanged()
}
override fun onDestroyView() {
super.onDestroyView()
_binding=null
}
NewsViewModel
class NewsViewModel: ViewModel() {
val newsService = KopraMobileService().getNewsApi()
var job: Job? = null
val exceptionHandler = CoroutineExceptionHandler { _, throwable ->
onError("Exception handled: ${throwable.localizedMessage}")
}
val newsList = MutableLiveData<List<NewsModel>>()
val loadError = MutableLiveData<String?>()
val loading = MutableLiveData<Boolean>()
fun refresh() {
fetchNews()
}
private fun fetchNews() {
loading.postValue(true)
job = CoroutineScope(Dispatchers.IO + exceptionHandler).launch {
val response = newsService.getNewsList()
withContext(Dispatchers.Main) {
if (response.isSuccessful) {
newsList.postValue(response.body()?.data)
loadError.postValue(null)
loading.postValue(false)
} else {
onError("Error : ${response.message()} ")
}
}
}
loadError.postValue("")
loading.postValue( false)
}
private fun onError(message: String) {
loadError.postValue(message)
loading.postValue( false)
}
override fun onCleared() {
super.onCleared()
job?.cancel()
}
}
NewsAdapter
NewsAdapter(
var itemsCells: List<NewsModel?> = emptyList(),
var shimmer: Boolean ,
) :
RecyclerView.Adapter<ViewHolder>() {
private lateinit var context: Context
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NewsHomeViewHolder {
context = parent.context
return NewsHomeViewHolder(
NewsItemHomeBinding.inflate(LayoutInflater.from(parent.context), parent, false)
)
}
override fun onBindViewHolder(holder: NewsHomeViewHolder, position: Int) {
holder.bind(itemsCells[position]!!)
}
inner class NewsHomeViewHolder(private val binding: NewsItemHomeBinding) :
ViewHolder(binding.root) {
fun bind(newsItem: NewsModel) {
binding.newsItemFlat.newsTitle.text = newsItem.name
binding.newsItemFlatShimmer.newsTitle.text = newsItem.name
binding.newsItemFlat.newsSummary.text = newsItem.name
binding.newsItemFlatShimmer.newsSummary.text = newsItem.name
if (shimmer) {
binding.layoutNewsItemFlat.visibility = View.INVISIBLE
binding.layoutNewsItemFlatShimmer.visibility = View.VISIBLE
binding.layoutNewsItemFlatShimmer.startShimmer()
} else {
binding.layoutNewsItemFlat.visibility = View.VISIBLE
binding.layoutNewsItemFlatShimmer.visibility = View.INVISIBLE
}
}
}
override fun getItemCount(): Int {
return itemsCells.size
}
I hope someone can help me to solve the problem. thanks, sorry for my English.
You have 3 different LiveDatas, right? One with a list of news data, one with a loading error message, and one with a loading state.
You set up an Observer for each of these, and that observer function gets called whenever the LiveData's value updates. That's important, because here's what happens when your request succeeds, and you get some new data:
if (response.isSuccessful) {
newsList.postValue(response.body()?.data)
loadError.postValue(null)
loading.postValue(false)
}
which means newsList updates, then loadError updates, then loading updates.
So your observer functions for each of those LiveDatas run, in that order. But you're not testing the new values (except for null checks), so the code in each one always runs when the value updates. So when your response is successful, this happens:
newsList observer runs, displays as successful, calls getDataNews
loadError observer runs, value is null so nothing happens
loading observer runs, value is false but isn't checked, displays as loading, calls getDataNewsShimmer
So even when the response is successful, the last thing you do is display the loading state
You need to check the state (like loading) before you try to display it. But if you check that loading is true, you'll have a bug in fetchNews - that sets loading = true, starts a coroutine that finishes later, and then immediately sets loading = false.
I'd recommend trying to create a class that represents different states, with a single LiveData that represents the current state. Something like this:
// a class representing the different states, and any data they need
sealed class State {
object Loading : State()
data class Success(val newsList: List<NewsModel>?) : State()
data class Error(val message: String) : State()
}
// this is just a way to keep the mutable LiveData private, so it can't be updated
private val _state = MutableLiveData<State>()
val state: LiveData<State> get() = _state
private fun fetchNews() {
// initial state is Loading, until we get a response
_state.value = State.Loading
job = CoroutineScope(Dispatchers.IO + exceptionHandler).launch {
val response = newsService.getNewsList()
// if you're using postValue I don't think you need to switch to Dispatchers.Main?
_state.postValue(
// when you get a response, the state is now either Success or Error
if (response.isSuccessful) State.Success(response.body()?.data)
else State.Error("Error : ${response.message()} ")
)
}
}
And then you just need to observe that state:
// you don't need to create an Observer object, you can use a lambda!
newsViewModel.state.observe(viewLifecycleOwner) { state ->
// Handle the different possible states, and display the current one
// this lets us avoid repeating 'binding.frameNews' before everything
with(binding.frameNews) {
// You could use a when block, and describe each state explicitly,
// like your current setup:
when(state) {
// just checking equality because Loading is a -singleton object instance-
State.Loading -> {
rvNews.visibility = View.VISIBLE
rvNews.isNestedScrollingEnabled = false
itemNewsLayoutFailed.visibility = View.GONE
getDataNewsShimmer()
}
// Error and Success are both -classes- so we need to check their type with 'is'
is State.Error -> {
rvNews.visibility = View.INVISIBLE
itemNewsLayoutFailed.visibility = View.VISIBLE
btnNewsFailed.setOnClickListener {
newsViewModel.refresh()
}
}
is State.Success -> {
rvNews.visibility = View.VISIBLE
rvNews.isNestedScrollingEnabled = true
itemNewsLayoutFailed.visibility = View.GONE
// Because we know state is a Success, we can access newsList on it
// newsList can be null - I don't know how you want to handle that,
// I'm just treating it as defaulting to size == 0
// (make sure you make this visible when necessary too)
if (state.newsList?.size ?: 0 == 0) root.visibility = View.GONE
else getDataNews(state.newsList)
}
}
// or, if you like, you could do this kind of thing instead:
itemNewsLayoutFailed.visibility = if (state is Error) VISIBLE else GONE
}
}
You also might want to break that display code out into separate functions (like showError(), showList(state.newsList) etc) and call those from the branches of the when, if that makes it more readable
I hope that makes sense! When you have a single value representing a state, it's a lot easier to work with - set the current state as things change, and make your observer handle each possible UI state by updating the display. When it's Loading, make it look like this. When there's an Error, make it look like this
That should help avoid bugs where you update multiple times for multiple things, trying to coordinate everything. I'm not sure why you're seeing that problem when you reload after an error, but doing this might help fix it (or make it easier to see what's causing it)

FirestoreRecyclerAdapter getItemCount() always returns 0

Here is my Adapter class code:
class SearchPeopleAdapter(user: FirestoreRecyclerOptions<User>) :
FirestoreRecyclerAdapter<User, SearchPeopleAdapter.ViewHolder>(user) {
private var mUser : FirestoreRecyclerOptions<User>? = null
private var mOptions: FirestoreRecyclerOptions<User>? = null
private var mSnapshots: ObservableSnapshotArray<User>? = null
init {
mUser = user
}
fun firestoreRecyclerAdapter(user: FirestoreRecyclerOptions<User>?) {
mOptions = user
mSnapshots = user!!.snapshots
if (mOptions!!.owner != null) {
mOptions!!.owner!!.lifecycle.addObserver(this)
}
}
override fun startListening() {
if (!mSnapshots!!.isListening(this)) {
mSnapshots!!.addChangeEventListener(this);
}
}
override fun stopListening() {
mSnapshots!!.removeChangeEventListener(this)
notifyDataSetChanged()
}
//Inflate the xml
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
LayoutInflater.from(parent.context)
.inflate(R.layout.search_people_list_item, parent, false))
}
//Bind every dataView to the xml based on the Int value
override fun onBindViewHolder(viewHolder: ViewHolder, holderNumber: Int, user: User) {
viewHolder.apply {
itemView.search_people_person_list_name.text = user.Name
itemView.search_people_person_username.text = user.UserName
}
viewHolder.bind(user)
}
override fun getItemCount(): Int {
return mSnapshots!!.size
}
//Adds functionality to each View (aka ViewHolder) which is every person downloaded
inner class ViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView!!), View.OnClickListener {
//We are downloading User Objects so this Variable will be assigned to the UserObject downloaded
var currentUser : User? = null
//When the class is initiated this function is called which sets an OnClickListener to each View
init {
itemView!!.setOnClickListener(this)
}
//The Data from the Object is used to Populate the TextViews
fun bind(model: User) {
currentUser = model
itemView.search_people_person_list_name.text = model.Name
itemView.search_people_person_username.text = model.UserName
//If the user has set a profilePhoto then download & populate it with Glide
if ( model.ProfilePhotoChosen ) {
CompanionObjects.getPersonProfilePhotoStorageRef(model.Uid).downloadUrl.addOnSuccessListener {
val downloadUrl = it.toString()
Glide.with(itemView)
.load(downloadUrl)
.into(itemView.search_people_list_profile_image)
}.addOnFailureListener {
Timber.i("unable to retrieve your profile photo")
}
}
//Clear the View with the Glide.with(View).clear() method as the view will be reused and the photo
//might also get reused unnecessarily
else {
Glide.with(itemView).clear(itemView.search_people_list_profile_image)
}
}
//The onClick function is called when the View is clicked, in this case we are starting
// an Intent with the Intent Extra of userId to the PersonProfile Activity
// which will check for the IntentExtras and Populate the elements
override fun onClick(v: View?) {
val userId = currentUser!!.Uid
Timber.i("The click is $userId")
val intent = Intent(v!!.context, PersonProfileActivity::class.java)
intent.putExtra(CompanionObjects.USER_ID_INTENT_EXTRA, userId)
v.context.startActivity(intent)
}
}
}
Here are 2 of the methods in the Activity class, Inspite of calling the onStart and onStop method, the itemCount method always returns 0
override fun onStop() {
adapter!!.stopListening()
super.onStop()
}
//Retrieves data from Firestore and assigns the retrieved data to the search People Adapter
private fun retrieveDataFromFirestore(searchQuery : String) {
mFirestore = FirebaseFirestore.getInstance()
//Assigns the Collection Name from which needs to be queried
//the where conditions ensure to query a userDocument whose userName starts with the query entered in the searchField
val userNameQuery = mFirestore.collection(CompanionObjects.USERS_COLLECTION_NAME)
.whereGreaterThanOrEqualTo("userName", searchQuery)
.whereLessThanOrEqualTo("userName", "$searchQuery\uF7FF")
//Assigns the query to the User Objects that are related to Firestore
users = FirestoreRecyclerOptions.Builder<User>()
.setQuery(userNameQuery, User::class.java)
.build()
//Assigns the Firestore queried data to the search People Adapter
adapter = SearchPeopleAdapter(users!!)
registerAdapterObserver()
adapter!!.firestoreRecyclerAdapter(users!!)
adapter!!.startListening()
search_people_list.setHasFixedSize(true)
search_people_list.hasFixedSize()
search_people_list.layoutManager = LinearLayoutManager(this)
search_people_list.adapter = adapter
persistSearchQueryString(searchQuery)
}
When I call getItemCount method in the Activity class. It always returns 0 even thou the adapter does hold Views. How do I retrieve the exact count in the Adapter
Please make sure mSnapshots = user!!.snapshots produces items.
In fun retrieveDataFromFirestore(searchQuery : String) after adding items in adapter!!.firestoreRecyclerAdapter(users!!), you are not notifying RecyclerView to update.
So, don't forget to call
adapter!!.notifyDataSetChanged();
Your code might looks like this:
private fun retrieveDataFromFirestore(searchQuery : String) {
mFirestore = FirebaseFirestore.getInstance()
//Assigns the Collection Name from which needs to be queried
//the where conditions ensure to query a userDocument whose userName starts with the query entered in the searchField
val userNameQuery = mFirestore.collection(CompanionObjects.USERS_COLLECTION_NAME)
.whereGreaterThanOrEqualTo("userName", searchQuery)
.whereLessThanOrEqualTo("userName", "$searchQuery\uF7FF")
//Assigns the query to the User Objects that are related to Firestore
users = FirestoreRecyclerOptions.Builder<User>()
.setQuery(userNameQuery, User::class.java)
.build()
//Assigns the Firestore queried data to the search People Adapter
adapter = SearchPeopleAdapter(users!!)
registerAdapterObserver()
adapter!!.firestoreRecyclerAdapter(users!!)
adapter!!.startListening()
adapter!!.notifyDataSetChanged(); //<------- Add this line---------
search_people_list.setHasFixedSize(true)
search_people_list.hasFixedSize()
search_people_list.layoutManager = LinearLayoutManager(this)
search_people_list.adapter = adapter
persistSearchQueryString(searchQuery)
}
Ok I solved this, Here is the code:
private fun retrieveDataFromFirestore(searchQuery : String) {
mFirestore = FirebaseFirestore.getInstance()
//Assigns the Collection Name from which needs to be queried
//the where conditions ensure to query a userDocument whose userName
starts with the query entered in the searchField
val userNameQuery = mFirestore.collection(CompanionObjects.USERS_COLLECTION_NAME)
.whereGreaterThanOrEqualTo(userName, searchQuery.toLowerCase())
.whereLessThanOrEqualTo(userName, "${searchQuery.toLowerCase()}\uF7FF")
//Assign the Query to the user variable
users = FirestoreRecyclerOptions.Builder<User>()
.setQuery(userNameQuery, User::class.java)
.build()
//Assigns the Firestore queried data to the search People Adapter
adapter = object : SearchPeopleAdapter(users!!) {
//Need to create a class Body because it is open and this gives
//option to override its onDataChanged method in the Activity rather than in its adapter class
override fun onDataChanged() {
if ( itemCount == 0 ) {
search_people_list.visibility = View.INVISIBLE
retrieving_progress.visibility = View.INVISIBLE
empty_search_users_text.visibility = View.VISIBLE
//If was not searching with name field then prompt search with name field
if ( !searchingWithNameField ) {
//Code to add formatting options to the text like underline it
val content = SpannableString(getString(R.string.search_with_name_instead))
content.setSpan(UnderlineSpan(), 0, content.length, 0)
change_search_field_text.text = content
} else
//If was not searching with username field then prompt search with username field
{
//Code to add formatting options to the text like underline it
val content = SpannableString(getString(R.string.search_with_username_instead))
content.setSpan(UnderlineSpan(), 0, content.length, 0)
change_search_field_text.text = content
}
change_search_field_text.visibility = View.VISIBLE
} else {
//The adapter count is not 0 so show the recyclerView and hide the progress bar, emptyText, Change Search field Text etc.
search_people_list.visibility = View.VISIBLE
retrieving_progress.visibility = View.INVISIBLE
empty_search_users_text.visibility = View.INVISIBLE
change_search_field_text.visibility = View.INVISIBLE
//Should persist only if there is a result from the query ofCourse
persistSearchQueryStringAndSearchField(searchQuery)
}
}
}
adapterCreated = true
adapter!!.startListening()
adapter!!.notifyDataSetChanged()
//Make the progress bar visible and invisible soon as a document is added to the adapter
registerAdapterObserver()
search_people_list.setHasFixedSize(true)
search_people_list.hasFixedSize()
search_people_list.layoutManager = LinearLayoutManager(this)
search_people_list.adapter = adapter
}
So, What I did was made the adapter class open, then created an instance of the Adapter in the Activity and called the OnDataChanged() method in the Activity which watches for the itemCount in the Adapter. This way I am able to retrieve the correct the adapterCount value.

RecyclerView not updating after delete/update of a note

PROBLEM - After a note is deleted from second activity, on returning back to first activity(this activity displays notes), changed made to note i.e deleted or edited does not shows change UNLESS the app is restarted and onCreate() method is recalled. If I change my device orientation, then the data gets updated.
How my code works - Basically, my app consists of two activities. First(Main) Activity is where recyclerview resides, this activity handles display of notes by fetching data from SQLite database and displays in form of cardViews. Those cardViews are click able, each cardView when clicked takes to Second(Reference) activity and a corresponding data is loaded into that activity. Now a user has a choice to either make changes to current note or to delete it. If a user clicks on delete button, data of the corresponding note is deleted from SQLite database. On deletion, app automatically goes back to Main activity. HOWEVER, the deleted note does not appears to be deleted in the main activity not until the app is restarted and onCreate method is called.
I have gone through multiple almost similar questions on the site but they do not appear to fit my needs. I am a beginner in Android development so if you could please explain it a little would greatly help me. Thank you.
MAIN ACTIVITY
class MainActivity : AppCompatActivity() {
//START OF EX-INITIALIZATIONS
var dbHandler: PediaDatabase? = null
var adapter: PediaAdapter? = null
var layoutManager: RecyclerView.LayoutManager? = null
var list: ArrayList<UserNotes>? = ArrayList()
var listItems: ArrayList<UserNotes>? = ArrayList()
val PREFS_NAME: String = "MYPREFS"
var myPrefs: SharedPreferences? = null
var first_run: Boolean = true
val REQUEST_CODE: Int = 1
var deletedNoteID: Int = 0
var deletedNoteAdapterPos: Int = 0
//END OF EX-INITIALIZATIONS
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
}
//START OF IN-INITIALIZATIONS
dbHandler = PediaDatabase(this)
list = ArrayList<UserNotes>()
listItems = ArrayList()
adapter = PediaAdapter(this, listItems!!)
layoutManager = LinearLayoutManager(this)
recyclerViewID.adapter = adapter
recyclerViewID.layoutManager = layoutManager
//END OF IN-INITIALIZATIONS
//DATA POPULATION STARTS HERE
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()
//DATA POPULATION ENDS HERE
if(dbHandler!!.totalNotes() == 0) {
recyclerViewID.visibility = View.GONE
}
else{
recyclerViewID.visibility = View.VISIBLE
showWhenEmptyID.visibility = View.GONE
}
}//end onCreate
override fun onRestart() {
super.onRestart()
overridePendingTransition(R.anim.slide_out, R.anim.slide_in)
}
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
//return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if(item!!.itemId == R.id.add_note_menu){
var isNewNote = Intent(this, ReferenceActivity::class.java)
isNewNote.putExtra("isNewNote", true)
startActivityForResult(isNewNote, REQUEST_CODE)
}
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()
}
}
REFERENCE ACTVITY
class ReferenceActivity : AppCompatActivity() {
var dbHandler: PediaDatabase? = null
var note = UserNotes()
var existingNote = UserNotes()
var noteExisted: Boolean = false
var cardID: Int = 0
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.RED
dbHandler = PediaDatabase(this)
var data = intent
var isNewNote = intent
if(isNewNote != null)
if(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"
}
}//end onCreate()
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 =
dbHandler!!.updateNote(existingNote)
var dataToMain = this.intent
dataToMain.putExtra("cardID", cardID)
dataToMain.putExtra("cardAdapterPos", cardAdapterPos)
setResult(Activity.RESULT_OK, dataToMain)
finish()
}
else
{
if(TextUtils.isEmpty(title) && TextUtils.isEmpty(text))
{
finish()
}
else
{
if(TextUtils.isEmpty(title))
title = "No title"
note.noteTitle = title
note.noteText = text
dbHandler!!.createNote(note)
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
//return super.onCreateOptionsMenu(menu)
}
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)
var 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)
}
}
you need to update your list items inside your adapter;
not sure how it works on kotlin, but I use something like this:
after a note update call adapter.updateItens(itens);
MyAdapter extendes RecyclerView.Adapter<MyViewHolder>
private List<MyItem> elements;
MyAdapter(){
this.elements = new ArrayList<>();
}
void updateElements(List<MyItem> itens){
Collections.sort(itens, new SortByName());
this.elements.clear();
this.elements.addAll(itens);
notifyDataSetChanged();
}
you can do even better if instead of notifyDataSetChanged(), you implement a DiffUtil;
After making changes to the data in the database, the RecyclerViewAdapter needs to be given a new list of data. This should be done in onRestart(), so that once you navigate back to MainActivity from SecondActivity, the RecyclerView is populated with the updated data. Try copying the code that populates the RecyclerView and put it into onRestart(). The reason why it was only updating when onCreate() was called is because that's the only place where you do anything to the view.

Categories

Resources