Dynamically add items to listview in Android

June 20, 2012
By

In this article we are creating an application in which user inputs items to a ListView via an EditText widget. An extension to this article is available in the article titled “Deleting Selected Items from ListView in Android“, ¬†where deleting a listview item is discussed.


1. Create an Android project namely “AddItemsDynamically”

New Android Project

Figure 1: New Android Project


2. Select build target for the application

Select Android Build Target

Figure 2: Select Android Build Target


3. Enter application details

Enter application details

Figure 3: Enter application details


4. Open and update the file res/values/strings.xml with the highlighted text given below

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, MainActivity!</string>
    <string name="app_name">AddItemsDynamically</string>
    <string name="hintTxtItem">Enter an item here ...</string>
    <string name="lblBtnAdd">Add Item</string>
    <string name="txtEmpty">List is empty</string>
</resources>

5. Open and update the file res/layout/main.xml with the given below code


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

    <EditText
        android:id="@+id/txtItem"
        android:layout_width="240dp"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:hint="@string/hintTxtItem"
    />

    <Button
        android:id="@+id/btnAdd"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/lblBtnAdd"
        android:layout_toRightOf="@id/txtItem"
    />

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/txtItem"
    />

    <TextView
        android:id="@android:id/empty"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/txtItem"
        android:text="@string/txtEmpty"
        android:gravity="center_horizontal"
    />

</RelativeLayout>


6. Open and update the file src/in/wptrafficanalyzer/additemsdynamically/MainActivity.java with the given below code


package in.wptrafficanalyzer.additemsdynamically;

import java.util.ArrayList;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;

/** Note that here we are inheriting ListActivity class instead of Activity class **/
public class MainActivity extends ListActivity {

    /** Items entered by the user is stored in this ArrayList variable */
    ArrayList<String> list = new ArrayList<String>();

    /** Declaring an ArrayAdapter to set items to ListView */
    ArrayAdapter<String> adapter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        /** Setting a custom layout for the list activity */
        setContentView(R.layout.main);

        /** Reference to the button of the layout main.xml */
        Button btn = (Button) findViewById(R.id.btnAdd);

        /** Defining the ArrayAdapter to set items to ListView */
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);

        /** Defining a click event listener for the button "Add" */
        OnClickListener listener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText edit = (EditText) findViewById(R.id.txtItem);
                list.add(edit.getText().toString());
                edit.setText("");
                adapter.notifyDataSetChanged();
            }
        };

        /** Setting the event listener for the add button */
        btn.setOnClickListener(listener);

        /** Setting the adapter to the ListView */
        setListAdapter(adapter);
    }
}


7. Execute the application

Application in execution

Figure 4: Application in execution


8. Download the source


9. References

http://developer.android.com/guide/index.html


How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: , , ,

30 Responses to Dynamically add items to listview in Android

  1. Kannan on July 2, 2012 at 5:35 pm

    Hi,
    I am new to this dynamic list view, I want to do long press action in this dynamic list view, How can i achieve this?.Thanks in advace.

    • george on July 2, 2012 at 6:35 pm

      append the given below code to onCreate() method


      OnItemLongClickListener itemLongClickListener = new OnItemLongClickListener() {
      @Override
      public boolean onItemLongClick(AdapterView arg0, View arg1,
      int arg2, long arg3) {
      Toast.makeText(getBaseContext(), "Long Clicked:" + adapter.getItem(arg2) , Toast.LENGTH_SHORT).show();
      return false;
      }
      };

      ListView lv = getListView();
      lv.setOnItemLongClickListener(itemLongClickListener);

  2. maryam on July 31, 2012 at 1:20 pm

    hi
    how can i add items from edittext to spinner in my app?
    thanx a lot

  3. vaishali on September 14, 2012 at 11:46 pm

    Hey George!!..

    awesome tutorial, but there’s a question in mind that whenever am running my application again, the items i’ve added have been removed and then i again have to insert new items, is this the reason you have used notifyDataSetchanged(), as i am also not getting the proper use of this method, i’ve googled it also, but still no result.. pls explain..

    thanx in advance!!..

  4. kim on May 18, 2013 at 12:26 pm

    this sample is very very good! Clear, and easy.

  5. Jr on June 27, 2013 at 8:05 am

    Is it possible if i add an item here and be able to save it even if i restart the app? when i open the app and be able to see the items i already added?

  6. rajender on July 18, 2013 at 5:10 pm

    thank you it was very use full to me…
    and how to delete that item please send code to my mail id

  7. Ivan on October 17, 2013 at 10:18 pm

    How can I allow users to add image & text to a listview??? I hope you can help.

  8. Korey on October 25, 2013 at 8:36 pm

    How can I add the EditText input in 1 Activity to a ListView in a different Activity?

  9. Haryanto on December 2, 2013 at 8:18 am

    error

    The type new DialogInterface.OnClickListener(){} must implement the inherited abstract method DialogInterface.OnClickListener.onClick(DialogInterface, int)

    how to fix it?

  10. Bidhu Prasad Panda on December 2, 2013 at 3:04 pm

    Hi
    Thanks for this blog.
    I want to know how i can create a listview where each row having edit and delete button .
    if i want to edit the row i can edit by pressing rdit button.
    pls give one example using mysql database.

  11. Jaura on May 27, 2014 at 7:45 am

    Hi, I want to be able to add another EditText to create ‘Item Details’, just below the Item. Then put in a checkbox to select the Item and its details, and bring it forward to the next page. Any idea how I could do that?

  12. ron on October 10, 2014 at 3:43 pm

    How to save and load the Listview items Dynamically , do you know of any way?,Great tutorials love to see an example

  13. Deepak on October 31, 2014 at 2:13 pm

    Really very simple to understand!

  14. Sarita on December 15, 2014 at 11:27 am

    Can we retrieve the Input/Output stream of UsbDevice?

  15. Jose Garza on March 30, 2015 at 12:03 am

    Hi, thanks for your example.
    I want to change the color of the row when it have a specific text, something like when the text have numbers it change to red color. any idea how I could do that?

  16. gaurav meghanathi on May 21, 2015 at 6:27 pm

    hi George Mathew i am new to android. i am try to when user click on imagebutton to call second activity.then second activity content a form value for example student name,mark1,mark2,mark3 input from user on submit button and send back their value to main activity to display listview. but i can’t find a way to store student name and there percentage to view in listview in dynamic.

  17. sam on June 3, 2015 at 2:36 am

    Hi Thank you for the example.
    If we have a listview in one activity and edittext in another activity how to append the values like a todo list. Here you are using the same activity.
    Please do reply.

    Thanks in advance.

  18. Rudresh on June 3, 2015 at 1:11 pm

    Hi thanks for your example

    I want to know how to align left and right alignment rows inside Listview

  19. anugya on June 10, 2015 at 4:15 pm

    HI,
    thank you for wonderful post. Could you help me with this please ?
    I have a custom listview with the item,price,image with the checkbox. HOw can I send the selected items and price of listview (the items are selected via the checkbox) to the next activity when the button is clicked.

  20. vandana on July 25, 2015 at 11:51 am

    setListAdapter(adapter);

    this line showing error

  21. vandana on July 25, 2015 at 11:52 am

    showing this message

    “The method setListAdapter(ArrayAdapter) is undefined for the type grid”

  22. A.S.Krishna on November 8, 2015 at 11:44 am

    How to add relativelayout dynamically to list view as an item ??

  23. sarah on November 21, 2015 at 1:04 am

    how can I add switch button instate of adding text?

  24. swativasagadekar on May 17, 2016 at 8:43 pm

    Hi I want to add radio button with two spinners dynamically in listview.plz help

  25. ronx on June 20, 2016 at 5:06 pm

    How would you save this list items to a text file ?

  26. vikash patel on June 23, 2016 at 10:32 am

    how can I add Image view and Delete Button on each row of the listview.?

Leave a Reply

Your email address will not be published. Required fields are marked *

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner