ValueEventListener is not working as expected

I am trying to display data stored in Firebase in an AutoCompleteTextView dropdown. I am using ValueEventListener for this purpose . According to the ValueEventListener documentation ,

You can use the onDataChange () method to read a static snapshot of the content along a given path as they existed at the time of the event. This method runs once, when the listener is attached, and again every time the data, including children, changes.

Unfortunately, in my case, onDataChange () is only triggered when the data changes (that is, when new data is added). This means AutoCompleteTextView does not display the dropdown menu without any changes to the data in Firebase. I want onDataChange () to run the first time the Listener is called and every time the data changes. I would like to know where I am going wrong. The following code appears inside the onCreateView of a fragment

daTags.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            //Basically, this says "For each DataSnapshot *Data* in dataSnapshot, do what inside the method.
            for (DataSnapshot tagNameSnapshot : dataSnapshot.getChildren()) {
                //Get the suggestion by childing the key of the string you want to get.
                String ValueTagName = tagNameSnapshot.child(getResources().getString(R.string.Child_AppData_Tags_TagName)).getValue(String.class);
                //Add ValueTagName (Value pulled from Firebase for the above Key) to TagList
                //Is better to use a List, because you don't know the size of the iterator returned by dataSnapshot.getChildren() to initialize the array
                tagList.add(ValueTagName);

                //Initialize AutoCompleteTextView and define Adapter
                ArrayAdapter<String> adapterAutoComplete = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, tagList);
                actv_tagName.setAdapter(adapterAutoComplete);

                //Get TagsCount using dataSnapshot and display TagsCount in TextView
                TagsCount = dataSnapshot.getChildrenCount() + "";
                tv_tagsCount.setText(TagsCount);
            }
        });

      

thank

+1


source to share


1 answer


I think I figured out the problem. To make it work, I will have to move the following lines of code outside of the For loop

ArrayAdapter<String> adapterAutoComplete = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, tagList);
actv_tagName.setAdapter(adapterAutoComplete);

      



Inside the For loop, the adapter is updated for each loop. Placing the above code outside of the loop fixes the problem.

0


source







All Articles