Wednesday, May 29, 2013

Populating ListView with ArrayList

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

There are multiple ways to populate the ListView items, we can do this using ArrayAdapter, BaseAdapter etc.


Populating list with with DataBase  and Custome Adapter is already posted

Polpulating ListView With DataBase
Populating ListView with Custom Adapter


Populating ListView With Custom Adapter Example

In this Post I will discuss how to populate ListView directly with ArrayList .
We will populate the ListView with ArrayList of Animals here  and also handle the click event on Item, we will show the Toast with Animal name which is clicked




main.xml





<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="#4D9494"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView
        android:id="@+id/textView1"
        android:layout_marginTop="80dp"
        android:gravity="center_horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Populating ListView with ArrayList Example"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button

       android:id="@+id/butttonShowAnimal"
        android:layout_marginTop="25dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Show Animals List"
        />
   

</LinearLayout>



animal_list.xml     

( For AnimalListActivity to show Animal Names, this layout contains only a ListView)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:orientation="vertical" >
   
    <ListView
        android:id="@+id/listViewAnimals"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:dividerHeight="0.1dp"
        android:divider="#0000CC"
        >
    </ListView>
    

</LinearLayout>

MainActivity.java

From this Activity when you click   Show Animals List , AnimalListActivty will start which showa the list of Animals.


public class MainActivity extends Activity
{
       
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
             super.onCreate(savedInstanceState);
             setContentView(R.layout.main);
            
                   // Get The Refference Of Button  
             Button btnShowAnimal=(Button)findViewById(R.id.buttonShowAnimal);
                        
          
            // Set OnClick Listener on  button  and start AnimalListActivity when clicked on Button
             btnShowAnimal.setOnClickListener(new View.OnClickListener() {
                   
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                       
                        /// Create Intent for AnimalListActivity and Start The Activity
                        Intent intentAnimalList=new Intent(getApplicationContext(),AnimalListActivity.class);
                        startActivity(intentAnimalList);
                    }
                });
    }
}

ShowAnimalsListActivity.java

(this Activity will inflate the animal_list layout and show  the List of Animals)

public class ShowAnimalsListActivity extends Activity
{
   
        ArrayList<String> animalsNameList;
        public void onCreate(Bundle saveInstanceState)
        {
                super.onCreate(saveInstanceState);
                setContentView(R.layout.animal_list);
                

               // Get the reference of ListViewAnimals
                ListView animalList=(ListView)findViewById(R.id.listViewAnimals);
               
               
                 animalsNameList = new ArrayList<String>();
                 getAnimalNames();
                 // Create The Adapter with passing ArrayList as 3rd parameter
                 ArrayAdapter<String> arrayAdapter =     
                 new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, animalsNameList);
                 // Set The Adapter
                 animalList.setAdapter(arrayAdapter);
                
                 // register onClickListener to handle click events on each item
                 animalList.setOnItemClickListener(new OnItemClickListener()
                    {
                             // argument position gives the index of item which is clicked
                            public void onItemClick(AdapterView<?> arg0, View v,int position, long arg3)
                            {
                               
                                    String selectedAnimal=animalsNameList.get(position);
                                    Toast.makeText(getApplicationContext(), "Animal Selected : "+selectedAnimal,   Toast.LENGTH_LONG).show();
                                 }
                    });
        }
       
        void getAnimalNames()
        {
            animalsNameList.add("DOG");
            animalsNameList.add("CAT");
            animalsNameList.add("HORSE");
            animalsNameList.add("ELEPHANT");
            animalsNameList.add("LION");
            animalsNameList.add("COW");
            animalsNameList.add("MONKEY");
            animalsNameList.add("DEER");
            animalsNameList.add("RABBIT");
            animalsNameList.add("BEER");
            animalsNameList.add("DONKEY");
            animalsNameList.add("LAMB");
            animalsNameList.add("GOAT");
           
           
        }
}



                             



How to Populate ListView with DataBase

Populating ListView with DataBase




 

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.






8 comments:

  1. This has several typos in the code, and crashes on Android 4.1.1

    Would recommend fixing this guide, or avoiding it.

    ReplyDelete
  2. I DON'T KNOW WHAT TO SAY

    ReplyDelete
  3. Nice Tutorial, thanks a lot!!
    Can you explain what the second parameter is please?
    ArrayAdapter arrayAdapter =
    new ArrayAdapter(this,android.R.layout.simple_list_item_1, animalsNameList);

    ReplyDelete
    Replies
    1. Second item is the name of .xml file in which we defined Textview under layout location. This will make the data of Arraylist displayed in Textview for each data record

      Delete
    2. This isn't working.Something wrong!

      Delete
  4. This isn't working

    ReplyDelete