user3314337
user3314337

Reputation: 341

ValueEventListener not Working as expected

I am trying to display the data stored in Firebase, in AutoCompleteTextView's Dropdown. For this purpose, I am using the ValueEventListener. According to the documentation of ValueEventListener,

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

Unfortunately, in my case onDataChange() is triggered only when data the is changed(that is, when new data is added). This means the AutoCompleteTextView doesn't display the dropdown without any change to the data in Firebase. What I want, is for the onDataChange() to trigger for the first time when 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 onCreateView of Fragment

daTags.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            //Basically, this says "For each DataSnapshot *Data* in dataSnapshot, do what's 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);
            }
        });

Thanks

Upvotes: 1

Views: 845

Answers (1)

user3314337
user3314337

Reputation: 341

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

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

When inside the For loop, the adapter gets updated for every loop. Placing the above code outside For loop, overcomes the issue.

Upvotes: 0

Related Questions