[Android Note] The Observer mode in the data adapter, Android adapter

Source: Internet
Author: User

[Android Note] The Observer mode in the data adapter, Android adapter
To display data in ListView, the data Adapter is used. When we delete an entry of the ListView, the data source in the data adapter will inevitably change. At this time, we will call the yydatasetchanged method provided by the adapter class to notify the listview that the data has changed and request to be re-drawn. This actually uses a common design pattern, namely the observer pattern.
Before analyzing the observer mode involved in the data adapter, we should first briefly understand what the observer mode is.Definition of observer Mode: Defines a one-to-many dependency between objects, so that every time an object changes state, all objects dependent on it will be notified and automatically updated.
The above is the class diagram of the observer mode. In the Subject class, use the Attach/Detach method to bind/unbind one or more Observer objects. When a Subject has an event of interest to the Observer, subject will call the notify y method to notify all bound Observer objects and call its update method to update data.
Next we try to analyze the observer mode in the data adapter. Here we can trace the source code from notifyDataSetChanged in BaseAdapter. When this method is located, we find that there is only one line of code, that is, the notifyChanged method of the mDataSetObservable object is called.

 public void notifyDataSetChanged() {        mDataSetObservable.notifyChanged();    }
This mDataSetObservable is the object to be observed. It is a DataSetObservable type. Let's take a look at its implementation:
package android.database;public class DataSetObservable extends Observable<DataSetObserver> {     public void notifyChanged() {        synchronized(mObservers) {            for (int i = mObservers.size() - 1; i >= 0; i--) {                mObservers.get(i).onChanged();            }        }    }}
It can be seen that the onChanged callback method of each observer is called in its notifyChanged method. This mObservers is the observer set, which is defined in the parent class Observable of DataSetObservable. In addition, here, the generic type specifies that the observer type must be DataSetObserver. Open the Observable source code:
package android.database;import java.util.ArrayList;public abstract class Observable<T> {    protected final ArrayList<T> mObservers = new ArrayList<T>();    public void registerObserver(T observer) {        if (observer == null) {            throw new IllegalArgumentException("The observer is null.");        }        synchronized(mObservers) {            if (mObservers.contains(observer)) {                throw new IllegalStateException("Observer " + observer + " is already registered.");            }            mObservers.add(observer);        }    }    public void unregisterObserver(T observer) {        if (observer == null) {            throw new IllegalArgumentException("The observer is null.");        }        synchronized(mObservers) {            int index = mObservers.indexOf(observer);            if (index == -1) {                throw new IllegalStateException("Observer " + observer + " was not registered.");            }            mObservers.remove(index);        }    }    ...}
This class defines an observer set of the ArrayList type and provides two methods to register/unregister an observer. In fact, it calls the remove/add method of the set. Here we understand that calling the notifyDataSetChanged method of the adapter will eventually notify all registered observers to call the onChanged method of each observer. If ListView wants to update the interface after deleting an entry, it must have registered an observer before that, and the observer's onChanged method will inevitably have the interface re-painting code. The setAdapter method is used to deal with the adapter in ListView. As you can imagine, this method certainly includes the code for registering the observer. Based on this idea, we locate the setAdapter method of ListView:
 public void setAdapter(ListAdapter adapter) {       ... ...        super.setAdapter(adapter);        if (mAdapter != null) {           ... ...            mDataSetObserver = new AdapterDataSetObserver();            mAdapter.registerDataSetObserver(mDataSetObserver);         ... ...        } else {          ... ...        }        requestLayout();    }
Sure enough, we found the code for registering the observer in this method, but the observer here is of the AdapterDataSetObserver type, and the Adapter requires the DataSetObserver type. Obviously, adapterDataSetObserver is a subclass of DataSetObserver. The class is defined in the parent class AbsListView of ListView:
class AdapterDataSetObserver extends AdapterView<ListAdapter>.AdapterDataSetObserver {        @Override        public void onChanged() {            super.onChanged();            if (mFastScroller != null) {                mFastScroller.onSectionsChanged();            }        }   ... ...    }
The AdapterDataSetObserver in the AbsListView inherits the AdapterDataSetObserver in the AdapterView class. In the end, we find AdapterDataSetObserver in AdapterView:
 class AdapterDataSetObserver extends DataSetObserver {        private Parcelable mInstanceState = null;        @Override        public void onChanged() {            mDataChanged = true;            mOldItemCount = mItemCount;            mItemCount = getAdapter().getCount();            if (AdapterView.this.getAdapter().hasStableIds() && mInstanceState != null                    && mOldItemCount == 0 && mItemCount > 0) {                AdapterView.this.onRestoreInstanceState(mInstanceState);                mInstanceState = null;            } else {                rememberSyncState();            }            checkFocus();            requestLayout();        }  ... ...    }
As you can see, this class does inherit DataSetObserver and calls requestLayout in onChanged to refresh the layout. Here we understand the entire process, and also see the use of the observer mode in the actual project, it is indeed very powerful. A picture is attached to facilitate your understanding.










Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.