Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Fixes to "Retrieving a List of Contacts" Android tutorial by Google: https://developer.android.com/training/contacts-provider/retrieve-names.html
// Fixes to compilation errors in "Define the onItemClick() method" section
// Doesn't compile
Cursor cursor = parent.getAdapter().getCursor();
// Fixed (not sure if this is the cleanest way though)
Cursor cursor = ((SimpleCursorAdapter) parent.getAdapter()).getCursor();
// Doesn't compile
mContactId = getLong(CONTACT_ID_INDEX);
// Fixed
mContactId = cursor.getLong(CONTACT_ID_INDEX);
// Doesn't compile
mContactKey = getString(CONTACT_KEY_INDEX);
// Fixed. Note that the constant defined earlier in the tutorial is LOOKUP_KEY_INDEX
mContactKey = cursor.getString(LOOKUP_KEY_INDEX);
@HansDaigle
Copy link

HansDaigle commented Mar 28, 2017

Well done! Thanks for that.

@sahalsajjad
Copy link

sahalsajjad commented Oct 3, 2017

Thanks!

@mostafahadian
Copy link

mostafahadian commented May 28, 2018

Also another one:

mContactsList = (ListView) getActivity().findViewById(R.layout.contact_list_view);

is wrong and should be changed to

mContactsList = (ListView) getActivity().findViewById(R.id.list);

Thanks.

@max-pla
Copy link

max-pla commented Jan 31, 2019

Thanks. It works

@HerbertBodner
Copy link

HerbertBodner commented Jun 27, 2019

That really helped me. Thanks, man!

@HerbertBodner
Copy link

HerbertBodner commented Jun 28, 2019

In addition, the onItemClick event is not triggering. In the contacts_list_item.xml you have to set following properties for the TextView:

android:clickable="false"
android:focusable="false"

@jadeye
Copy link

jadeye commented Nov 9, 2019

Also in contacts_list_view.xml:

    `android:id="@android:id/list"`

Should be:

    `android:id="@+id/list"`

As the fragment does not recognize this (in @mostafahadian's remark):

   `mContactsList = (ListView) getActivity().findViewById(R.id.list);`

@Nekr0w
Copy link

Nekr0w commented Nov 26, 2019

Hi there,

I'm getting an error trying to get the ListView object.

contactsList = (ListView) getActivity().findViewById(R.id.list); ... contactsList.setAdapter(cursorAdapter);

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference

Do I need to use setContentView() method ?

@jadeye
Copy link

jadeye commented Nov 27, 2019

Hi there,

I'm getting an error trying to get the ListView object.

contactsList = (ListView) getActivity().findViewById(R.id.list); ... contactsList.setAdapter(cursorAdapter);

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference

Do I need to use setContentView() method ?

Try SO answer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment