14.01.2013 Views

Android™ Application Development - Bahar Ali Khan

Android™ Application Development - Bahar Ali Khan

Android™ Application Development - Bahar Ali Khan

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 5: Intents, Broadcast Receivers, Adapters, and the Internet<br />

126<br />

4. Return to the ContactPicker Activity. Override the onCreate method, and extract the data<br />

path from the calling Intent.<br />

@Override<br />

public void onCreate(Bundle icicle) {<br />

super.onCreate(icicle);<br />

setContentView(R.layout.main);<br />

Intent intent = getIntent();<br />

String dataPath = intent.getData().toString();<br />

4.1. Create a new data URI for the people stored in the contact list, and bind it to the List<br />

View using a SimpleCursorArrayAdapter.<br />

The SimpleCursorArrayAdapter lets you assign Cursor data, used by Content Providers, to<br />

Views. It’s used here without further comment but is examined in more detail later in this chapter.<br />

final Uri data = Uri.parse(dataPath + “people/”);<br />

final Cursor c = managedQuery(data, null, null, null, null);<br />

String[] from = new String[] {People.NAME};<br />

int[] to = new int[] { R.id.itemTextView };<br />

SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,<br />

R.layout.listitemlayout,<br />

c,<br />

from,<br />

to);<br />

ListView lv = (ListView)findViewById(R.id.contactListView);<br />

lv.setAdapter(adapter);<br />

4.2. Add an ItemClickListener to the List View. Selecting a contact from the list should<br />

return a path to the item to the calling Activity.<br />

lv.setOnItemClickListener(new OnItemClickListener() {<br />

public void onItemClick(AdapterView parent, View view, int pos,<br />

long id) {<br />

// Move the cursor to the selected item<br />

c.moveToPosition(pos);<br />

// Extract the row id.<br />

int rowId = c.getInt(c.getColumnIndexOrThrow(“_id”));<br />

// Construct the result URI.<br />

Uri outURI = Uri.parse(data.toString() + rowId);<br />

Intent outData = new Intent();<br />

outData.setData(outURI);<br />

setResult(Activity.RESULT_OK, outData);<br />

finish();<br />

}<br />

});<br />

4.3. Close off the onCreate method.<br />

}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!