Home > other >  Autocomplete Textview updates suggestion list if the user adds a new item
Autocomplete Textview updates suggestion list if the user adds a new item

Time:10-19

I have a Firestore project where the user can add a new item and upon adding it, it should be added on the suggestion list on my search view's autocomplete TextView.

But, the suggestions are not updated whenever I add a new item.

Here's my snippet:

val searchView = binding.toolbar.searchView
        val productsRef = Firebase.firestore.collection("products")
        val productList = mutableListOf<String>()
        //get all products name in firebase
        productsRef.get()
            .addOnSuccessListener { documents ->
                for(document in documents){
                    productList.add(document["name"].toString())
                }
            }

        val arrayAdapter = ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, productList)
        val autoComplete = searchView.findViewById<AutoCompleteTextView>(R.id.search_src_text)
        autoComplete.setAdapter(arrayAdapter)

Is there some way that this code would run again whenever there is a change in my collection particularly when adding a new item/document?

Edit: The list doesn't seem to include my newly added item when I try to search for it. But when I close my app and search for my added item, it shows up. What I intended to do is to sync the list whenever I try to add a new item so that I don't have to close my app for me to see it on the search view's suggestion box.

Thanks!

CodePudding user response:

According to your comment:

I guess the problem is I am calling this code on my onCreate method which only runs once when the app was launched. When I try to go to a new activity where I add a new item, the above code doesn't run anymore. This could be the reason why my array does not include the newly added document since this snippet only runs once.

That's the expected behavior since you are using a Query#get() call which only:

Executes the query and returns the results as a QuerySnapshot.

This means that it only gets the data precisely once.

Is there a Firestore method where it listens for any changes?

If you want to listen for real-time updates that take place in your "products" collection, then you should consider using Query#addSnapshotListener() which:

Starts listening to this query using an Activity-scoped listener.

As explained in the official documentation:

Please also note, that there is also a library called Firebase-UI for Android, that can help you achieve exactly what you want.

CodePudding user response:

You'd need to notify, when the data is ready to be presented (needs to run on the UI thread):

autoComplete.getAdapter().notifyDataSetChanged()

... and keep using the same adapter, not assign a new one over and over.

Obviously, that productList would need to be maintained properly.

  • Related