Advanced Adapter in Android with Example

This Android Program lets you create an Adapter in an Application using Java.

Here is source code of the Program to create an Adapter in an Application. The program is successfully compiled and run on a Windows system using Eclipse Ide. The program output is also shown below.

Adapter

Adapter

Now our previous implementation of an Adapter was okay , but there was a flaw in it or it had many time consuming operations.Now let us understand the interal working of an adapter and how it works and provides data to the list View object that we create in our program.

Adapters call the getView() method which returns a view for each item that is within the adapter view. The layout format and the corresponding data for each item in the adapter view is set in the getView() method. Now, as you can understand that how bad our application would be if getView() returns a new View every time it is called , it will be a performance nightmare. Creating a new view is very expensive in Android as you will need to loop through the view hierarchy (using the find ViewbyID () method) and then inflate the view to finally display it on the screen.It also puts a lot of pressure on the garbage collector. That is because when the user is scrolling through the list, if a new view is created; the old view (since it is not recycled) is not referenced and becomes a candidate to be picked up by the garbage collector. So what Android does is that it recycles the views and reuses the view that goes out of focus.

advertisement
advertisement

And Every View which get inflated from an XML layout file will result in a Java object. Creating Java objects is expensive with regards to time and memory consumption. In addition using the findViewById() method is relatively time consuming, even though it is not as bad as XML inflating. This class describes how to reduce these operations to make your ListView faster. The default Android adapters like ArrayAdapter are already performance optimized.

A ListView usually contains more data than the number of displayed rows. If suppose a user scrolls the list , the associated views would be scrolled out of the visible area , now the java object which represents these rows can be re-used for displaying the new rows rows that the user wants to see. Now this can be done in Android (re-using the views ) via the convertView paramater. A performance optimized adapter assigns the new data to the convertView. This avoids inflating an XML file and creating new Java objects.

Note
In case no View is available for reuse, Android will pass null to the convertView parameter. Therefore our adapter implementation need to check for this.

Main Activity

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
 
package com.example.advanced_adapter;
 
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.view.Menu;
 
public class MainActivity extends ListActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        String str[] = new String[] {"C","C++","Java","Andorid"};
                AdvancedAdapter adapter = new AdvancedAdapter(this, str);
                setListAdapter(adapter);
    }
}

AdvancedAdapter

 
package com.example.advanced_adapter;
 
import java.util.zip.Inflater;
 
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
 
public class AdvancedAdapter extends ArrayAdapter<String> {
 
    private final Context context;
    private final String[] lang;
 
    public AdvancedAdapter(Context context, String lang[]) {
        super(context, R.layout.rowlayout, lang);
        // TODO Auto-generated constructor stub
        this.context = context;
        this.lang = lang;
    }
 
    static class Holder {
        public TextView text;
        public ImageView img;
        }
 
        @Override
         public View getView(int position, View convertView, ViewGroup parent) {
               // TODO Auto-generated method stub
               View row;
                 if (convertView == null) {
                        LayoutInflater li = (LayoutInflater) context
                                         .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                        row = li.inflate(R.layout.rowlayout, parent, false);
                        Holder holder = new Holder();
                        holder.text = (TextView) row.findViewById(R.id.label);
                        holder.img = (ImageView) row.findViewById(R.id.icon);
                        row.setTag(holder);
                  } else {
                     row = convertView;
        }
 
        Holder holder = (Holder) row.getTag();
                String str = lang[position];
                holder.text.setText(str);
 
        if (str.startsWith("C")) {
                     holder.img.setImageResource(R.drawable.c_pic);
        } else if (str.startsWith("Java")) {
                     holder.img.setImageResource(R.drawable.java);
        } else if (str.startsWith("Android")) {
                     holder.img.setImageResource(R.drawable.ic_launcher);
        } else {
            // c++
                    holder.img.setImageResource(R.drawable.c_prog);
        }
 
        return row;
    }
 
}

RowLayout.xml

advertisement
 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >
 
    <ImageView
        android:id="@+id/icon"
        android:layout_width="100px"
        android:layout_height="100px"
        android:layout_marginLeft="4px"
        android:layout_marginRight="10px"
        android:layout_marginTop="4px"
        android:src="@drawable/ic_launcher" >
    </ImageView>
 
    <TextView
        android:id="@+id/label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@+id/label"
        android:textSize="80px" >
        <extView>
 
</LinearLayout>

advanced_adapter

advertisement

Sanfoundry Global Education & Learning Series – 100+ Java Android Tutorials.

If you wish to look at all Tutorials, go to Java Android Tutorials.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.