21.10.2016 Views

android-6-for-programmers-3rd

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

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

9.12 AddEditFragment Class 373<br />

9.12.6 View.OnClickListener saveContactButtonClicked and<br />

Method saveContact<br />

When the user touches this Fragment’s FloatingActionButton, the saveContactButton-<br />

Clicked listener (Fig. 9.45, lines 152–162) executes. Method onClick hides the keyboard<br />

(lines 157–159), then calls method saveContact.<br />

151 // responds to event generated when user saves a contact<br />

152 private final View.OnClickListener saveContactButtonClicked =<br />

153 new View.OnClickListener() {<br />

154 @Override<br />

155 public void onClick(View v) {<br />

156 // hide the virtual keyboard<br />

157 ((InputMethodManager) getActivity().getSystemService(<br />

158 Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(<br />

159 getView().getWindowToken(), 0);<br />

160 saveContact(); // save contact to the database<br />

161 }<br />

162 };<br />

163<br />

164 // saves contact in<strong>for</strong>mation to the database<br />

165 private void saveContact() {<br />

166 // create ContentValues object containing contact's key-value pairs<br />

167 ContentValues contentValues = new ContentValues();<br />

168 contentValues.put(Contact.COLUMN_NAME,<br />

169 nameTextInputLayout.getEditText().getText().toString());<br />

170 contentValues.put(Contact.COLUMN_PHONE,<br />

171 phoneTextInputLayout.getEditText().getText().toString());<br />

172 contentValues.put(Contact.COLUMN_EMAIL,<br />

173 emailTextInputLayout.getEditText().getText().toString());<br />

174 contentValues.put(Contact.COLUMN_STREET,<br />

175 streetTextInputLayout.getEditText().getText().toString());<br />

176 contentValues.put(Contact.COLUMN_CITY,<br />

177 cityTextInputLayout.getEditText().getText().toString());<br />

178 contentValues.put(Contact.COLUMN_STATE,<br />

179 stateTextInputLayout.getEditText().getText().toString());<br />

180 contentValues.put(Contact.COLUMN_ZIP,<br />

181 zipTextInputLayout.getEditText().getText().toString());<br />

182<br />

183 if (addingNewContact) {<br />

184 // use Activity's ContentResolver to invoke<br />

185 // insert on the AddressBookContentProvider<br />

186<br />

187<br />

Uri newContactUri = getActivity().getContentResolver().insert(<br />

Contact.CONTENT_URI, contentValues);<br />

188<br />

189 if (newContactUri != null) {<br />

190 Snackbar.make(coordinatorLayout,<br />

191 R.string.contact_added, Snackbar.LENGTH_LONG).show();<br />

192<br />

193 }<br />

listener.onAddEditCompleted(newContactUri);<br />

Fig. 9.45 | View.OnClickListener saveContactButtonClicked and method saveContact.<br />

(Part 1 of 2.)

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

Saved successfully!

Ooh no, something went wrong!