我正在尝试用所有者的电子邮件填充 ArrayList。我在一个片段中这样做。这是我的代码:
public class ItemDetailFragment extends Fragment implements
LoaderManager.LoaderCallbacks<Cursor> {
ArrayList<String> emails = new ArrayList<String>();
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getLoaderManager().initLoader(0, null, this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myFragmentView = inflater.inflate(R.layout.formal_email_layout,
container, false);
return myFragmentView;
}
public Loader<Cursor> onCreateLoader(int id, Bundle arguments) {
return new CursorLoader(getActivity(),
// Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath(
ContactsContract.Profile.CONTENT_URI,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY),
ProfileQuery.PROJECTION,
// Select only email addresses.
ContactsContract.Contacts.Data.MIMETYPE + " = ?",
new String[]{ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE},
// Show primary email addresses first. Note that there won't be
// a primary email address if the user hasn't specified one.
null);
}
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
List<String> emails = new ArrayList<String>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
emails.add(cursor.getString(ProfileQuery.ADDRESS));
// Potentially filter on ProfileQuery.IS_PRIMARY
cursor.moveToNext();
}
Log.d("test", cursor.getString(ProfileQuery.ADDRESS));
}
public void onLoaderReset(Loader<Cursor> cursorLoader) {
}
private interface ProfileQuery {
String[] PROJECTION = {
ContactsContract.CommonDataKinds.Email.ADDRESS,
ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
};
int ADDRESS = 0;
int IS_PRIMARY = 1;
}
}
我基本上使用了这里给出的例子,我只是把它改编成一个片段。
当片段被午餐时,应用程序崩溃,我得到这个错误:
07-05 12:27:55.235: W/dalvikvm(23217): threadid=1: thread exiting with uncaught exception (group=0x40c2f1f8)
07-05 12:27:55.235: E/AndroidRuntime(23217): FATAL EXCEPTION: main
07-05 12:27:55.235: E/AndroidRuntime(23217): android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
(我的设备上有一个 Gmail 帐户)