Android @ Kiowok

Adapters and ListViews

ListView

A ListView is a very easy and common mechanism used to display large amounts of data. The data is often in the form of an ArrayList, or coming out of a database (in a cursor). Here we'll user an array adapter to connect a ListView to an ArrayList.

Set Up the ListView

Add a ListView to the Activity's user interface in res/layout. The example below assumes the ListView has been given an id of listView.

The onCreate method:

  • Gets a reference to the listView object
  • Shows some sample manipulations of the ArrayList
  • Creates an ArrayAdapter, and connects the ArrayList and the ListView via the ArrayAdapter
  • Sets up an event listener for the ListView

 

public class ThingListActivity extends Activity {
    private static final String TAG = "*** YOUR TAG ***";
    
    ListView listView;
    ArrayList<String> arr = new ArrayList();
	 ArrayAdapter<String> adapter;

	 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jobs_your_name);
        
		listView = (ListView) findViewById(R.id.listView);
		
		arr.add("milk");
		arr.add("eggs");
		arr.add("potatoes");
		arr.add("ham");
		arr.remove(1);
		
		adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arr);
		listView.setAdapter(adapter);
		
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int position,
					long id) {
				String s = (String) adapter.getItem(position);
				Toast.makeText(getApplicationContext(), position + ": "+ s, Toast.LENGTH_LONG).show();
			}
		});
    }
}

Changes

If the data associated with a list view changes -- such as the addition or deletion of an element -- then the adapter must be notified of the change:

				adapter.notifyDataSetChanged();
    
Top