Wednesday, February 6, 2013

Populating ListView With DataBase

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

ListView with SQLiteDatabse


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

Have a look at my previous post
Populating ListView with Custom Adapter
Populating ListView with ArrayList
ExpandableListView In Android

To learn Basic of Android Animation  go to  Android Animation Basics 

If you want to show Items in ListView with Header you should use ExpandableListView .  To Learn how to use ExpandableListView    read my post   ExpandableListView In Android

ListView with DataBase Example


In this example I have created a listView  and populated it with DataBAse.
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.


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>




ListViewWithDatabaseActivity 


public class ListViewWithDatabaseActivity extends Activity
{

   
        ListView listViewPhoneBook;
        Context context;
         @Override
        protected void onCreate(Bundle savedInstanceState)
         {
                 super.onCreate(savedInstanceState);
                 setContentView(R.layout.listview_activity_main);
                 context=this;
                 //get the ListView Reference
                 listViewSMS=(ListView)findViewById(R.id.listViewSMS);
                

                  //arrayColumns is the column name in your cursor where you're getting the data 
                  // here we are displaying  SMSsender Number i.e. address and SMSBody i.e. body

                  String[] arrayColumns = new String[]{"address","body"};
                  //arrayViewID contains the id of textViews
                  // you can add more Views as per Requirement
                  // textViewSMSSender is connected to "address" of arrayColumns
                  // textViewMessageBody is connected to "body"of arrayColumns

                  int[] arrayViewIDs = new int[]{R.id.textViewSMSSender,R.id.textViewMessageBody};
                    
                    
                  Cursor cursor;
                  
                    cursor = getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);
                  
                // create an Adapter with arguments layoutID, Cursor, Array Of Columns, and Array of ViewIds which is to be Populated
                  
                 SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.listview_each_item, cursor, arrayColumns, arrayViewIDs);
                 listViewSMS.setAdapter(adapter);
                
                
                
                 // To handle the click on List View 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();
                                }
                               
                            });
             }
 }


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.






30 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. I used tο bе able to find gοod
    information from уour сontеnt.


    my sіte; disque dur SSD

    ReplyDelete
  3. hello,
    i don't understand where in the code you are connecting to the database .
    I made a MySQL database on easyPHP and i'm trying to populate a listview from the database.

    Thank you

    ReplyDelete
    Replies
    1. Hi Niiaou
      Look carefully at lines
      // get the cursor
      cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

      // create an Adapter with arguments layoutID, Cursor, Array Of Columns, and Array of Views which is to be Populated
      // here we are connecting with database
      SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.each_contact, cursor, arrayColumns, arrayViewID);

      Delete
  4. Great beat ! I wish to apprentice while you amend your web site,
    how can i subscribe for a blog web site? The account helped me a acceptable deal.
    I had been a little bit acquainted of this your broadcast offered
    bright clear concept

    my site - tarot

    ReplyDelete
  5. Hello to all, it's actually a good for me to visit this web page, it includes valuable Information.

    Also visit my webpage ... tarot de Marseille ()

    ReplyDelete
  6. Your Blog is outstanding. Covered almost all common as well as advanced topics of android.

    ReplyDelete
  7. Your Blog is outstanding. Covered almost all basic to advanced topics of android. Thanks a lot.

    ReplyDelete
  8. exellent blog...but it is possible populating the list column vise rather than row vise???

    ReplyDelete
  9. i want to add delete botton delete the record from listview and database also how can i write the code for that
    please help me

    ReplyDelete
  10. Thank you for the auspicious writeup. It actually was a leisure account it.

    Look complicated to far introduced agreeable from you!
    However, how could we keep in touch?

    ReplyDelete
  11. Hello very nice site!! Guy .. Excellent .. Amazing ..
    I'll bookmark your website and take the feeds additionally?
    I am glad to find numerous useful info right here within the post, we need develop
    more strategies on this regard, thanks for sharing.
    . . . . .

    ReplyDelete
  12. Quality posts is the crucial to interest the visitors to pay a quick visit the web
    site, that's what this web site is providing.

    ReplyDelete
  13. Your method of describing the whole thing in this post is actually
    good, all be capable of without difficulty be aware of it,
    Thanks a lot.

    ReplyDelete
  14. Wow that was odd. I just wrote an incredibly long comment but after
    I clicked submit my comment didn't show up. Grrrr... well I'm not writing all that over again. Anyhow, just wanted to say superb blog!

    ReplyDelete
  15. Hey I know this is off topic but I was wondering
    if you knew of any widgets I could add to my blog that automatically tweet my
    newest twitter updates. I've been looking for a plug-in like this for quite some time and was
    hoping maybe you would have some experience with something
    like this. Please let me know if you run into anything.
    I truly enjoy reading your blog and I look forward to your new updates.

    ReplyDelete
  16. I need to to thank you for this wonderful read!!
    I absolutely loved every little bit of it. I've got you book-marked
    to check out new stuff you post…

    ReplyDelete
  17. Good blog you have here.. It's hard to find good quality
    writing like yours nowadays. I honestly appreciate people like you!
    Take care!!

    ReplyDelete
  18. You are so cool! I do not believe I've truly read a single thing like that before.
    So nice to find another person with unique thoughts on this topic.
    Seriously.. many thanks for starting this up.
    This website is one thing that is needed
    on the web, someone with some originality!

    ReplyDelete
  19. Hi there Dear, are you truly visiting this web site daily,
    if so then you will absolutely get good experience.

    ReplyDelete
  20. hello!,I love your writing so a lot! share we keep in touch more approximately your post on AOL?

    I require a specialist in this space to solve my problem. May be that's you!
    Taking a look ahead to peer you.

    ReplyDelete
  21. Hello just wanted to give you a quick heads up and let you know a
    few of the pictures aren't loading properly. I'm not sure
    why but I think its a linking issue. I've tried it in two different browsers and both show the same
    outcome.

    ReplyDelete
  22. Wow! This blog looks exactly like my old one! It's on a totally different topic but it has
    pretty much the same layout and design. Excellent choice of colors!

    ReplyDelete
  23. Hi there, just wanted to mention, I liked this article.

    It was helpful. Keep on posting!

    ReplyDelete
  24. My brother suggested I might like this website. He used
    to be totally right. This post actually made my day.
    You cann't consider just how so much time I had spent for this information! Thank you!

    ReplyDelete
  25. My partner and I stumbled over here coming from a different
    website and thought I might check things out. I like what I see so i am
    just following you. Look forward to exploring your web page again.

    ReplyDelete
  26. Hi! I've been reading your website for a while now and finally got the courage to go
    ahead and give you a shout out from Lubbock Tx!
    Just wanted to mention keep up the fantastic job!

    ReplyDelete
  27. Fantastic website. Plenty of useful info here. I am sending it to
    some pals ans additionally sharing in delicious. And
    certainly, thank you in your effort!

    ReplyDelete