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 etcIn 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;
}
}
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.
Thanks Kamlesh for such a easy and straight explanation.
ReplyDeleteAn Custom patch, also known as a cloth badge, is a piece of embroidery which is created by using a fabric backing and thread.
Deleteexcellent
ReplyDeleteexcellent. i had found so many tutorials but none was easy to understand. you made my day :D thanks
ReplyDeleteListView with custom items
ReplyDeleteAnonymous they was also a listView with custom item... but my problem is
ReplyDeletethey 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//
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
ReplyDeleteVery pretty man!
ReplyDeleteJust 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
Yes, If your table contains lot of records, then it could be a long operation, in that case you can use AsyncTask
DeleteI 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
ReplyDeleteThere are all sorts of items that really are mens fashion accessories. Visit This Site Right Here
ReplyDeleteWe love online stores that offer free shipping. Better still if they are able to offer free shipping Crockery, Perfumes, Jewellery, Mobile Accessories
ReplyDeleteYour 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
ReplyDeletery 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. Скрабирование тела
ReplyDeleteI 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
ReplyDeleteWe 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
ReplyDeleteI 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
ReplyDeleteAivivu đại lý vé máy bay, tham khảo
ReplyDeletevé máy bay đi Mỹ bao nhiêu
lịch bay từ california về việt nam
đăng ký bay từ canada về Việt Nam
các chuyến bay từ nhật bản về hà nội hôm nay
ve may bay vietnam airline tu han quoc ve viet nam
Vé máy bay từ Đài Loan về VN
giá khách sạn cách ly ở hà nội
vé máy bay chuyên gia sang Việt Nam
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.
ReplyDeleteNice 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.
ReplyDeleteVery 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.
ReplyDeleteWhat 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.
ReplyDeleteI 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.
ReplyDeleteI 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.
ReplyDeleteThe 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