Thursday 18 July 2013

Adapter


What is Base Adapter?

Now I am going to talk about very interesting topic i.e Adapter. Guys, many times we have seen list in various apps. How exiting is that to implement a ListView to create a list in that look which we want. Adapter plays very important role, when you implement a list view.
We use Adapter to bind data. Like suppose you have data of various students, and you wants to show that data in a list. It’s very simple, what you need to do is just wrap the data in a single object and bind this object with adapter. Well we will discuss all the procedure in brief.
Here we will see two ways to use adapter first one is by Array Adapter and the second by Base Adapter.



Array Adapter

Step 1:
Create a new xml file and name it  “main.xml”. In this xml I took a list view so that I can show data on a list. You can set height and width of ListView according to your requirement.

<script type=&quot;syntaxhighlighter&quot; class=&quot;brush: csharp&quot;>
<![CDATA[
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <ListView
        android:id="@+id/ll"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
       >
   </ListView>
</LinearLayout>


]]></script>
Step 2:  find your ListView in your Activity and make a Array of student’s name.
            lv = (ListView) findViewById(R.id.ll);
                        String[] names = { "Amitabh", "Akanksha", "Mohit", "Geeta", "Parul",
                                                "Ammu", "Atul", "Amit", ”Gourav” };



Step 3:  create a ArrayAdapter and set this adapter for your list view. This is the all, which you have done to create a list by using ArrayAdapter.
       ArrayAdapter<String> aadapter = new ArrayAdapter<String>(this,
                           android.R.layout.simple_list_item_1, names) {

              };

              lv.setAdapter(aadapter);



Step 4: if you want to perform any operation on click on any row of your list, so its quit simple just set setOnItemClickListener on your ListView.

lv.setOnItemClickListener(new OnItemClickListener() {
                                    public void onItemClick(AdapterView<?> parent, View view,
                                                            int position, long id) {
                                                view.setBackgroundColor(Color.BLUE);
                                                                        }
                        });







Step 5: Now you have completed all the actions to implement  ArrayAdapter”. Your Activity is now ready to use. At last just set this “AdapterEx1Activity” as Launcher Activity in your manifest file.
public class AdapterEx1Activity extends Activity {
            /** Called when the activity is first created. */
            static ListView lv;
            int pos;
            String spos;
            private int requestCode = 0;
            private int resultCode = 1;
            protected int itemId;

            static int i2 = 0;

            @Override
            public void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.main);

                        lv = (ListView) findViewById(R.id.ll);
                        String[] names = { "Amitabh", "Akanksha", "mohit", "Geeta", "Parul",
                                                "Ammu", "pavan", "Amit" };

                        ArrayAdapter<String> aadapter = new ArrayAdapter<String>(this,
                                                android.R.layout.simple_list_item_1, names) {

                        };

                        lv.setAdapter(aadapter);
                        lv.setOnItemClickListener(new OnItemClickListener() {
                                    public void onItemClick(AdapterView<?> parent, View view,
                                                            int position, long id) {
                                                view.setBackgroundColor(Color.BLUE);
                                                                        }
                        });
            }

}



Step 6 : you will get the following output on execute your code.




Base Adapter

Now what you think, the previous look is quite common?  If you want to make a look as you want, So be ready to do experiment with Base Adapter. The great benefit of Base Adapter is that, you can customize the look of your list and you can have more than one views in single row.


Step 7:
Create a new xml file and name it  “main.xml”. In this xml I took a list view so that I can show data on a list. You can set height and width of ListView according to your requirement.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <ListView
        android:id="@+id/ll"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
       >
   </ListView>
</LinearLayout>


Step 8: create a java file and name it “BaseAdapterEx” and inside your onCreate() method write this.
                        setContentView(R.layout.main);
                        ListView lv = (ListView) findViewById(R.id.ll);

Step 9:
Create a inner class inside your  “BaseAdapterEx”  and name it MyAdpter . Now extends  “BaseAdapter” in your inner class “MyAdpter”  implement all the unimplemented methods of BaseAdapter. Create two array and make them global so that you can use it inside your inner class also.
String[] names = {  "Akanksha",  "Geeta", "Parul", "Amrita", "mohit", "Amit" };

String[] status = {  "Rathore", "Darvai", "Chaturvedi","Sharma", "Jain" , "Dube" };


Step 10:
Create another xml file and name it “inflate”.Make this xml file like this :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>


Step 11:
Now I am going to use this inflate.xml file in “MyAdpter” class.
So make your “MyAdpter” class like this :

class akankshaAdapter extends BaseAdapter {

                        private TextView tv1;
                        private TextView tv2;
                        private ImageView img;

                        public int getCount() {
                                    // TODO Auto-generated method stub
                                    return names.length;
                        }

                        public Object getItem(int position) {
                                    // TODO Auto-generated method stub
                                    return null;
                        }

                        public long getItemId(int position) {
                                    // TODO Auto-generated method stub
                                    return 0;
                        }

                        public View getView(final int position, View v, ViewGroup parent) {
                                    // TODO Auto-generated method stub

                                    LayoutInflater lf = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
                                    v = lf.inflate(R.layout.inflate, null);

if(position==2) {
                                    v.setBackgroundColor(Color.CYAN);
}
                                    tv1 = (TextView) v.findViewById(R.id.textView1);
                                    tv2 = (TextView) v.findViewById(R.id.textView2);
                                    img = (ImageView) v.findViewById(R.id.imageView1);
                       
                                    System.out.print(position);
                                    tv1.setText(names[position]);
                                    tv2.setText(status[position]);
                                   
                                    tv1.setOnClickListener(new OnClickListener() {
                                               
                                                public void onClick(View v) {
                                                            // TODO Auto-generated method stub
                                                            String s=tv1.getText().toString();
                                                            System.out.println(s);
                                                           
                                                            Toast.makeText(getApplicationContext(), tv1.getText().toString(), 100).show();
                                                           
                                                }
                                    });

                                    return v;
                        }

            }


Step 12: Now your whole class structure will looks like
public class BaseAdapterEx extends Activity {
            String[] names = {  "Akanksha",  "Geeta", "Parul", "Amrita", "mohit", "Amit" };
       String[] status = {  "Rathore", "Darvai", "Chaturvedi","Sharma", "Jain" , "Dube" };

            @Override
            protected void onCreate(Bundle savedInstanceState) {

                        // TODO Auto-generated method stub
                        super.onCreate(savedInstanceState);

                        setContentView(R.layout.main);
                        ListView lv = (ListView) findViewById(R.id.ll);
                        akankshaAdapter akadp = new akankshaAdapter();
                        lv.setAdapter(akadp);

            }

            class  MyAdpter extends BaseAdapter {

                        private TextView tv1;
                        private TextView tv2;
                        private ImageView img;

                        public int getCount() {
                                    // TODO Auto-generated method stub
                                    return names.length;
                        }

                        public Object getItem(int position) {
                                    // TODO Auto-generated method stub
                                    return null;
                        }

                        public long getItemId(int position) {
                                    // TODO Auto-generated method stub
                                    return 0;
                        }

                        public View getView(final int position, View v, ViewGroup parent) {
                                    // TODO Auto-generated method stub

                                    LayoutInflater lf = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
                                    v = lf.inflate(R.layout.inflate, null);

if(position==2) {
                                    v.setBackgroundColor(Color.CYAN);
}
                                    tv1 = (TextView) v.findViewById(R.id.textView1);
                                    tv2 = (TextView) v.findViewById(R.id.textView2);
                                    img = (ImageView) v.findViewById(R.id.imageView1);
                       
                                    System.out.print(position);
                                    tv1.setText(names[position]);
                                    tv2.setText(status[position]);
                                   
                                    tv1.setOnClickListener(new OnClickListener() {
                                               
                                                public void onClick(View v) {
                                                            // TODO Auto-generated method stub
                                                            String s=tv1.getText().toString();
                                                            System.out.println(s);
                                                           
                                                            Toast.makeText(getApplicationContext(), tv1.getText().toString(), 100).show();
                                                           
                                                }
                                    });

                                    return v;
                        }

            }

}




Step 13: Declare this Activity as Launcher Activity in your manifest file and Run your project.



find the source code here