Search code examples
androidandroid-layoutfindviewbyid

Activity.findViewById() error "expected resource of type id" on R.layout object


I'm following this online tutorial to build a part of my app that will return a list of my contacts, but I've run in to a bit of an issue that doesn't seem to be mentioned anywhere in the tutorial.

This is in the class ContactsFragment, which is not the main activity of the project but returns the fragment for the main activity to use.

The error is occurring here...

public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    mContactsList =
        (ListView) getActivity().findViewById(R.layout.contacts_list_view); <--- here
    //...
}

The error reads "expected resource of type id", which is strange because Android Studio's intellisense is suggesting contacts_list_view to me when writing the code.

contacts_list_view.xml is a file in the res/layout directory that I have copied from the tutorial. Its contents is as below:

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

I'm pretty new to Android Studio and Android development in general, so there's a chance I'm missing something obvious. Feel free to point that out to me, or anything else that might fix my issue!

Thanks,

Mark


Solution

  • Change this line in the code:

    (ListView) getActivity().findViewById(R.layout.contacts_list_view); for (ListView) getActivity().findViewById(R.id.list);

    And in the .xml file:

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