Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1

Asking Android for a contact


Asking Android for a contact


Now you are going to create another implicit intent that enables users to choose a suspect
from their contacts. This implicit intent will have an action and a location where the relevant
data can be found. The action will be Intent.ACTION_PICK. The data for contacts is at
ContactsContract.Contacts.CONTENT_URI. In short, you are asking Android to help pick an item in
the contacts database.


You expect a result back from the started activity, so you will pass the intent via
startActivityForResult(...) along with a request code. In CrimeFragment.java, add a constant for
the request code and a member variable for the button.


Listing 15.11  Adding field for suspect button (CrimeFragment.java)


private static final int REQUEST_DATE = 0;
private static final int REQUEST_CONTACT = 1;
...
private Button mSuspectButton;
private Button mReportButton;


At the end of onCreateView(...), get a reference to the button and set a listener on it. Within the
listener’s implementation, create the implicit intent and pass it into startActivityForResult(...).
Also, once a suspect is assigned, show the name on the suspect button.


Listing 15.12  Sending an implicit intent (CrimeFragment.java)


public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
...
final Intent pickContact = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
mSuspectButton = (Button) v.findViewById(R.id.crime_suspect);
mSuspectButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivityForResult(pickContact, REQUEST_CONTACT);
}
});


if (mCrime.getSuspect() != null) {
mSuspectButton.setText(mCrime.getSuspect());
}


return v;
}


You will be using pickContact one more time in a bit, which is why you put it outside
mSuspectButton’s OnClickListener.

Free download pdf