ListView Examples
Basic Steps for Creating a Listview 1.Create a layout (e.g., a LinearLayout), with elements for –the ListView ( ) –the TextView ( ) –Other, e.g., a button to add a new item to the list 2.Create a layout for each item in the list (e.g., separate TextView for each field) 3.Implement the main activity (see following slides) Slide 2©SoftMoore Consulting
Implementing the Main Activity Declare that the main activity implements LoaderManager.LoaderCallbacks onCreateLoader(int id, Bundle args) onLoadFinished(Loader loader, D data) onLoaderReset(Loader loader) Decide which columns in the content provider get mapped to which views in the item layout private static final String[] VIEW_COLUMNS = { "name", "phone_num" }; private static final int[] VIEWS = { R.id.name, R.id.phoneNum }; Implement method onCreate() Implement other methods; e.g., onListItemClick(ListView l, View v, int position, long id) Slide 3©SoftMoore Consulting
Implementing public Loader onCreateLoader(int id, Bundle args) { Uri uri =... ; // CONTENT_URI; return new CursorLoader(this, uri, COLUMNS, null, null, null); public void onLoadFinished(Loader loader, Cursor data) { adapter.swapCursor(data); public void onLoaderReset(Loader loader) { adapter.swapCursor(null); } Slide 4©SoftMoore Consulting
Implementing the onCreate() Method Create an empty adapter for displaying the loaded data adapter = new SimpleCursorAdapter(this, R.layout.emergency_contact, null, VIEW_COLUMNS, VIEWS, 0); setListAdapter(adapter); Set up other listeners; e.g., –setOnItemLongClickListener() // delete item from list –setOnClickListener() // for button to add new item to list Initialize the loader manager in the activity’s onCreate() method. getLoaderManager().initLoader(0, null, this); Slide 5©SoftMoore Consulting Note: Need API level 11 or higher for SimpleCursorAdapter ’s constructor. these columns get mapped to these views
Advantages of Using Loaders They are available to every Activity and Fragment. They provide asynchronous loading of data. They monitor the source of their data and deliver new results when the content changes. They automatically reconnect to the last loader’s cursor when being recreated after a configuration change; i.e., they don't need to re-query their data. Slide 6©SoftMoore Consulting
Emergency Contacts (from Simple Database) Slide 7©SoftMoore Consulting
Contacts with Phone Numbers (Redacted) Slide 8©SoftMoore Consulting
Discussion See Handouts Main Activity for Emergency Contacts –uses a simple SQLite database Main Activity for Contacts with Phone Numbers –uses contacts provider –note use of adapter.setViewBinder to convert contact phone types (integers) into strings Slide 9©SoftMoore Consulting
Relevant Links List View Retrieving a List of Contacts Loaders Understanding the LoaderManager (part 2) Making ListView Scrolling Smooth Slide 10©SoftMoore Consulting