Wednesday, June 26, 2013

ListView with Custom Adapter

The Android Development Tutorials blog contains Basic as well as Advanced android tutorials.Go to Android Development Tutorials to get list of all Android Topics.


Populate ListView with Custom Adapter

ListView can be populated by ArrayAdapter, Database, ArrayList etc
In this post I will describe how to populate ListView using a Custom Adapter.

Have a look at my previous post
Populating ListView with Database
Populating ListView with ArrayList

ListView with Custom Adapter Example


In this example I have created a listView  and populated it with Custom Adapter.
Each of the ListView item contain two views
TextView SMS Sender : to show SMS Sender Number
TextView SMSBody : to show the SMS Body/content

Here the ListView shows the all the SMSes with Sender Number and SMSBody.

What we need to do ..
Create a Custom Adapter
and add/set  the adapter to ListView.

Add the following permission in your manifest file to read the SMS..
   <uses-permission android:name="android.permission.READ_SMS"/>
   <uses-permission android:name="android.permission.WRITE_SMS"/>


listview_activity_main.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#D1FFFF"
    android:orientation="vertical">
   
   
    <ListView
        android:id="@+id/listViewSMS"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:dividerHeight="0.1dp"
        android:divider="#0000CC"
        >
    </ListView>
   
  </LinearLayout>



listview_each_item.xml


<?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/textViewSMSSender"
        android:paddingLeft="2dp"
        android:textSize="20dp"
        android:textStyle="bold"
        android:textColor="#0000FF"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <TextView
        android:id="@+id/textViewMessageBody"
        android:paddingLeft="5dp"
        android:textColor="#5C002E"
        android:textSize="17dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

</LinearLayout>
   
  </LinearLayout>





ListViewMainActivity.java



public class ListViewMainActivity extends Activity
{
            ListView listViewSMS;
            Cursor cursor;
            SMSListAdapter smsListAdapter;
            Context context;
            @Override
            protected void onCreate(Bundle savedInstanceState)
            {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.listview_activity_main);
                   
                    context=this;
                    listViewSMS=(ListView)findViewById(R.id.listViewSMS);

                    cursor = getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);
                   
                    // Create the Adapter
                    smsListAdapter=new SMSListAdapter(this,cursor);
                   
                    // Set The Adapter to ListView
                    listViewSMS.setAdapter(smsListAdapter);
                    

                    // to handle click event on listView item
                    listViewSMS.setOnItemClickListener(new OnItemClickListener()
                    {
                            public void onItemClick(AdapterView<?> arg0, View v,int position, long arg3)
                            {
                                // when user clicks on ListView Item , onItemClick is called
                                // with position and View of the item which is clicked
                                // we can use the position parameter to get index of clicked item

                                TextView textViewSMSSender=(TextView)v.findViewById(R.id.textViewSMSSender);
                                TextView textViewSMSBody=(TextView)v.findViewById(R.id.textViewMessageBody);
                                String smsSender=textViewSMSSender.getText().toString();
                                String smsBody=textViewSMSBody.getText().toString();
                               
                                // Show The Dialog with Selected SMS
                                AlertDialog dialog = new AlertDialog.Builder(context).create();
                                dialog.setTitle("SMS From : "+smsSender);
                                dialog.setIcon(android.R.drawable.ic_dialog_info);
                                dialog.setMessage(smsBody);
                                dialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK",
                                        new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which)
                                    {
                                   
                                            dialog.dismiss();
                                            return;
                                }   
                                });
                                dialog.show();
                            }
                        });
       
            }
}



SMSListAdapter.java : The Custom Adapter


public class SMSListAdapter  extends BaseAdapter
{
   
    private Context mContext;
    Cursor cursor;
    public SMSListAdapter(Context context,Cursor cur)
    {
            super();
            mContext=context;
            cursor=cur;
          
    }
      
    public int getCount()
    {
        // return the number of records in cursor
        return cursor.getCount();
    }

    // getView method is called for each item of ListView
    public View getView(int position,  View view, ViewGroup parent)
    {
                    // inflate the layout for each item of listView
                    LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    view = inflater.inflate(R.layout.listview_each_item, null);
           
                    // move the cursor to required position
                    cursor.moveToPosition(position);
                   
                    // fetch the sender number and sms body from cursor
                    String senderNumber=cursor.getString(cursor.getColumnIndex("address"));
                    String smsBody=cursor.getString(cursor.getColumnIndex("body"));
                  
                    // get the reference of textViews
                    TextView textViewConatctNumber=(TextView)view.findViewById(R.id.textViewSMSSender);
                    TextView textViewSMSBody=(TextView)view.findViewById(R.id.textViewMessageBody);
                   
                    // Set the Sender number and smsBody to respective TextViews
                    textViewConatctNumber.setText(senderNumber);
                    textViewSMSBody.setText(smsBody);
                   
       
                    return view;
    }

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

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

ListView with Custom Adapter


 

New Advance Topics:                   Android LiveWallpaer Tutorial
Android ImageSwitcher                    Android TextSwitcher                                Android ViewFlipper
Android Gesture Detector               Handling/Detecting Swipe Events                Gradient Drawable
Detecting Missed Calls                    Hide Title Bar                                           GridView Animation
Android AlarmManager                 Android BootReceiver                       Vibrate Phone In a Desirable Pattern    
Developing for Different Screen Sizes           Showing Toast for Longer Time       Publishing your App
How to publish Android App on Google Play
Android TextWatcher                               Android ExpandableListView

 Beginning With Android
      Android : Introduction(What is Android)                                                              Configuring Eclipse for Android Development
     Creating Your First Android Project                                           Understanding Android Manifest File of your android app

 Advance Android Topics                                                              Customizing Android Views


Working With Layouts                                                                Working With Views

Understanding Layouts in Android                                                   Using Buttons and EditText in Android
Working with Linear Layout (With Example)                                     Using CheckBoxes in Android
Nested Linear Layout (With Example)                                              Using AutoCompleteTextView in Android                                                                                          Grid View
Relative Layout In Android                                                               ListView
Table Layout                                                                                   Android ProgressBar
Frame Layout(With Example)                                                          Customizing ProgressBar
Absolute Layout                                                                             Customizing Radio Buttons
Grid Layout                                                                                    Customizing Checkboxes In Android

Android Advance Views
Android Spinner                                                                           Android GalleryView
Android TabWidget                                                                      Android ExpandableListView

Android Components                                                                 Dialogs In Android

Activity In Android                                                                    Working With Alert Dialog
Activity Life Cycle                                                                    Adding Radio Buttons In Dialog
Starting Activity For Result                                                       Adding Check Boxes In Dialog
Sending Data from One Activity to Other in Android                    Creating Customized Dialogs in Android
Returning Result from Activity                                                   Creating Dialog To Collect User Input
Android : Service                                                                     DatePicker and TimePickerDialog
BroadcastReceiver                                                                   Using TimePickerDialog and DatePickerDialog In android

Menus In Android                                                                ListView:
Creating Option Menu                                                               Populating ListView With DataBase
Creating Context Menu In Android                                              Populating ListView with ArrayList
                                                                                               ListView with Custom Adapter

Toast                                                                                      Working With SMS
Customizing Toast In Android                                                       How to Send SMS in Android
Customizing the Display Time of Toast                                        How To Receive SMS
Customizing Toast At Runtime                                                  Accessing Inbox In Android
Adding Image in Toast
Showing Toast for Longer Time


TelephonyManager                                                            Storage: Storing Data In Android
Using Telephony Manager In Android                                          SharedPreferences In Android
                                                                                              Reading and Writing files to Internal Stoarage

Working With Incoming Calls                                       DataBase :  Introduction of SQLiteDataBase
How To Handle Incoming Calls in Android                                Working With Database in Android
How to Forward an Incoming Call In Android                            Creating Table In Android
CALL States In Android                                                          Inserting, Deleting and Updating Records In Table in Android


Miscellaneous
Notifications In Android
How To Vibrate The Android Phone
Sending Email In Android
Opening a webpage In Browser
How to Access PhoneBook In Android
Prompt User Input with an AlertDialog
How to Hide Title Bar In Android
How to show an Activity in Landscape or Portrait Mode only.
How to Set an Image as Wallpaper.






38 comments:

  1. Thanks Kamlesh for such a easy and straight explanation.

    ReplyDelete
    Replies
    1. An Custom patch, also known as a cloth badge, is a piece of embroidery which is created by using a fabric backing and thread.

      Delete
  2. excellent. i had found so many tutorials but none was easy to understand. you made my day :D thanks

    ReplyDelete
  3. Anonymous they was also a listView with custom item... but my problem is
    they was crash on "listview.setAdapter(.......) "they was return a null pointer exception... so please help me....i am also trying a solve this problem but they was not solving so if you any idea so reply me please//

    ReplyDelete
  4. In my experience working directly from the cursor in the adapter makes the list really slow and uses a lot of memory and when the list is long the app crashes while scrolling

    ReplyDelete
  5. Very pretty man!

    Just a question,
    "cursor = getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);"
    is a long operation, wouldn't it be better if you' do that in a new Thread or like Cursor Class defined is?

    So, as AsyncTask extension.

    Kind Regards

    ReplyDelete
    Replies
    1. Yes, If your table contains lot of records, then it could be a long operation, in that case you can use AsyncTask

      Delete
  6. I have read all the comments and suggestions posted by the visitors for this article are very fine,We will wait for your next article so only.Thanks! baseball cap companies

    ReplyDelete
  7. There are all sorts of items that really are mens fashion accessories. Visit This Site Right Here

    ReplyDelete
  8. We love online stores that offer free shipping. Better still if they are able to offer free shipping Crockery, Perfumes, Jewellery, Mobile Accessories

    ReplyDelete
  9. Your blogs further more each else volume is so entertaining further serviceable It appoints me befall retreat encore. I will instantly grab your rss feed to stay informed of any updates. Final Choice fashion store

    ReplyDelete
  10. ry to reduce stress filled situations. It is always easier said than done. Devote 30 minutes a day doing something you enjoy. Keep your temper under check and count to ten before losing your temper or getting aggravated. Π‘ΠΊΡ€Π°Π±ΠΈΡ€ΠΎΠ²Π°Π½ΠΈΠ΅ Ρ‚Π΅Π»Π°

    ReplyDelete
  11. I admire this article for the well-researched content and excellent wording. I got so involved in this material that I couldn’t stop reading. I am impressed with your work and skill. Thank you so much. custom patches

    ReplyDelete
  12. We do custom patches, embroidered patches, printed patches, custom Velcro patches, clothing labels, PVC patches, custom leather patches, custom keychains, and other promotional products. Following is an overview of our products. Custom Iron On Patches

    ReplyDelete
  13. I respect this article for the very much investigated substance and magnificent wording. I got so included in this material that I couldn't quit perusing. I am awed with your work and aptitude. Much obliged to you to such an extent. wholesale clothing

    ReplyDelete
  14. This is a topic that is close to my heart... Cheers!! A Turkish visa is a travel permit that allows foreign travelers to enter Turkey for tourism, business or business purposes. Getting a visa for Turkey online it's easy.

    ReplyDelete
  15. Nice post. Thank you for this work. The travelers need to apply visa for Kenya through online visa application. Check the details and read the guidelines before you fill up the application form and also can apply for kenya transit visa.

    ReplyDelete
  16. Very nice post, I definitely love this website, keep up the good work.. Passport holders from over 160 countries can obtain a e business visa India online. You can raed info about India business visa requirements online &. The application process is completely electronic, meaning that visitors do not need to be present in person at an embassy or consulate.

    ReplyDelete
  17. What a top notch information you’ve shared.. Thank you for this. Apply online for Azerbaijan online visa to travel Azerbaijan. Get visa online with 24/7 customer support.

    ReplyDelete
  18. I read this article, it is really informative. Your way of writing and clarifying things is very impressive.. India 5 years tourist visa fee depends on your nationality. You can check the Indian evisa website and check you are eligible country citizens and select your country and your visa type and see India 5 years tourist visa fee.

    ReplyDelete
  19. I am happy to see your work... Is that the same thing that I am trying to find... Have you heard of it? Some additional charges may apply in case of emergency in India visa fees and if you want to travel to India in an emergency, you need to check about it.

    ReplyDelete
  20. The content you published here is amazing and kindly keep publishing these type of content in details i'm thankful to you if you keep publishing this type of content.

    ReplyDelete
  21. Many online Baby Cloth/ retailers in Pakistan now offer organic and eco-friendly options. These choices are not only gentle on your baby's delicate skin but also environmentally conscious. Organic baby clothes are made from natural, pesticide-free materials, providing peace of mind to parents who prioritize sustainability.

    ReplyDelete
  22. Your blogs are like a burst of joy! Your thoughts are amazing, and I'm always excited to see what joyful insights you'll share next. Keep up the fantastic work!

    ReplyDelete
  23. I can't express how great today has been for me, all thanks to the immense pleasure of reading this highly informative article from the comfort of my home. Your hard work is truly appreciated!

    ReplyDelete
  24. Thank you for your generosity in sharing your wisdom, experiences, and reflections with your readers. Your blog is a treasured source of motivation and enlightenment, and I can hardly wait to see your future offerings.

    ReplyDelete
  25. I'm perpetually captivated by your blog! The way you seamlessly blend profound insights with eloquent storytelling, guiding readers on a well-planned journey through the universe of knowledge, is truly exceptional. Your knack for simplifying intricate ideas is genuinely commendable. Thank you for presenting this enlightening piece that deeply resonates with your audience.

    ReplyDelete
  26. Your blog post transported me to a world where ideas reign supreme and imagination knows no bounds. With each paragraph, you painted a vivid picture of possibility, challenging me to expand my thinking and embrace new ways of seeing the world.

    ReplyDelete
  27. Your post feels like a refreshing oasis in the desert of mundane content! Your insights are incredibly engaging, guiding readers through uncharted intellectual landscapes with clarity and finesse. The seamless integration of ideas forms a compelling narrative that keeps readers hooked until the very end. It's evident that you've poured your heart and soul into crafting this piece, resulting in a truly enjoyable reading experience.

    ReplyDelete
  28. Reading this post feels like stumbling upon a hidden oasis. It speaks to me in ways I didn't expect. Each word stirs emotions I've yet to fully process. Thank you for this unexpected source of enlightenment and connection.

    ReplyDelete
  29. I'm truly blown away by the depth of your analysis in this blog post. The way you unpacked such a complex topic is nothing short of remarkable. Reading your words felt like taking a journey into the depths of human consciousness. Your insights are both thought-provoking and enlightening, and I found myself nodding along with your points. It's clear that you're passionate about this subject, and your enthusiasm shines through in your writing. Thank you for sharing your wisdom with the world.

    ReplyDelete
  30. Impressive post! You have a gift for breaking down complex concepts into digestible parts. Your clear explanations and organized approach made the topic easy to follow. The real-world examples and personal anecdotes added a lot of value and made the content more relatable. I'm excited to read more from you. Great job!

    ReplyDelete
  31. This post is a game-changer! Your insights are like a beacon of light in a sea of darkness. I was spellbound by your words, eager to absorb every ounce of knowledge you shared. Thank you for making such a daunting topic seem so approachable. I'm feeling inspired and empowered.

    ReplyDelete
  32. Your posts feel like a comforting hug, pulling readers into a universe of engaging ideas and enchanting storytelling. Your writing effortlessly captures our attention, making us anticipate your next update. Keep spreading your light with your words; you have a knack for brightening even the most monotonous days.

    ReplyDelete
  33. This post was both informative and enjoyable to read. You did an excellent job of simplifying a complex topic. The mix of personal anecdotes and research-based information kept me hooked. Your focus on consistency as a vital element of success was very enlightening. I'm eager to put some of your suggestions into practice. Thank you for sharing such valuable insights. I'm looking forward to more posts from you. Keep up the fantastic work.

    ReplyDelete