Dynamically adding entries to ListView

To create a ListView, you creat an ArrayAdapter and supply it with Array list_of_string.
So to add entries all you need to do is, add entried to your Array list_of_string and then notify ur adapter by calling

 your_list_adapter.notifyDataSetChanged(); 

Heres the code

public class YourClass extends whatever{
  ArrayList<String> listItems=new ArrayList<String>();
  ArrayAdapter<String> adapter;
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,listItems);
    setListAdapter(adapter);
 }

 //To add stuff to list
 public void addItems(View v) {
   listItems.add("Whatever entry");
   adapter.notifyDataSetChanged();
 }
}

PS: You need to call notifyDataSetChanged() only in the UI thread.
To run a code in UI thread do this

((Activity)Your_Activity_Context_Variable).runOnUiThread(new Runnable() 
{
        public void run()
        {
           //Whatever Code to be run in UI thread ,Insert here
           //End      
        }
}
);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s