Android update content, views of parent activity from ListAdapter using Interface Example Tutorial

By | September 14, 2015

In this tutorial we will see a very good use case of Java Interface in our android application. Many times we need to update the contents of parent activity from a list adapter of the custom listview of the activity.

Use Case:
– When any changes are made in the single list item and we need to notify that change to the activity containing listview.


We can achieve this by providing a simple callback.

For this to work write a simple interface in your custom list adapter

public interface OnDataChangeListener{
    public void onDataChanged(int size);

and add a setter method for the OnDataChangeListener (also in the adapter)

OnDataChangeListener mOnDataChangeListener;
   public void setOnDataChangeListener(OnDataChangeListener onDataChangeListener){
      mOnDataChangeListener = onDataChangeListener;

Now let’s say you have a button view in your layout of each list item (every row of listview) i.e layout of your list adapter (not listview) and your have set onClicklistener for that button.
now add additional code to the following block in the adapter to that onClicklistener:

    if(mOnDataChangeListener != null){

in your activity you then need to register the listener

protected void onCreate(Bundle savedInstanceState) {
    adapter.setOnDataChangeListener(new Sold_item_adaptor.OnDataChangeListener(){
        public void onDataChanged(int size){
            //do whatever here

You have successfully added a listener which will update the content of your activity from custom list adapter.

11,295 total views, 1 views today

(Visited 6,588 times, 1 visits today)