getActivity().findViewById(R.layout.contacts_list_view) returns null

I have seen some similar question about this but it was all for different reasons (I think). The code I am using is taken from http://developer.android.com/training. I am trying to build a simple contacts app according to the tutorial: http://developer.android.com/training/contacts-provider/retrieve-names.html The part where I am getting the bug is Set up the CursorAdapter for the ListView. Это мой код:

@Override
    public void onActivityCreated(Bundle savedInstanceState) 
    {
        super.onActivityCreated(savedInstanceState);
        mContactsList = (ListView) getActivity().findViewById(R.layout.contacts_list_view);
        mCursorAdapter = new SimpleCursorAdapter(getActivity(), 
                R.layout.contacts_list_item, null, FROM_COLUMNS, TO_COLUMN, 0);
        mContactsList.setAdapter(mCursorAdapter);
        mContactsList.setOnItemClickListener(this);
        getLoaderManager().initLoader(0, null, this);
    }

Все файлы XML были введены в действие:

contact_list_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@android:id/text1"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:clickable="true"/>

contact_list_view.xml:

<?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"/>

My main activity consists of 2 FrameLayouts for the fragments to be put in. This is it's XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <FrameLayout
        android:id="@+id/frag_contacts"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:textColor="#0a20a3" >
    </FrameLayout>

    <FrameLayout 
        android:id="@+id/frag_contact_details"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textColor="#045011" />

</LinearLayout>

This is the onCreate of the activity:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ninth);
        if (findViewById(R.id.frag_contacts) != null)
        {
            if (savedInstanceState != null)
                return;
            ContactsFragment contactsFrag = new ContactsFragment();
            getFragmentManager().beginTransaction().add(R.id.frag_contacts, contactsFrag).commit();
        }
    }

also, this is the onCreateView of the fragment:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return inflater.inflate(R.layout.contacts_list_view, container, false);
    }

Now, sorry for the long post, some of it might be unnecessary, but the problem is that on the first snippet, getActivity().findViewById(R.layout.contacts_list_view) returns null all the time! Don't know what else to do. how else can I load data into the list, and what is wrong here? Заранее спасибо!


comment
your list is named android.R.id.list ...   -  person njzk2    schedule 11.12.2013


Ответы (6)


ты должен измениться

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

с

mContactsList = (ListView) getView().findViewById(R.id.contacts_list_view);

Since the ListView belongs to the View you return inside onCreateView.

person Blackbelt    schedule 11.12.2013
comment
Thanks blackbelt, but see my comment to Raghunandan - it did not help. - person Hummus; 11.12.2013
comment
@AndroidNewbie you need id R.id.contacts_list_view not layout - person Raghunandan; 11.12.2013
comment
@Androidnewbie, конечно, вы должны проверить на получение списка. Не для макета, который его содержит - person Blackbelt; 11.12.2013
comment
Yes, of course, I was thinking about it too, but this is how it was written in the tutorial. I must have missed something. Как вы можете видеть в контакте_лиз_view.xml, я (они) не определил новый идентификатор для ListView. therefore R.id.contacts_list_view does not exist in the project. Is it their mistake, or I had to do something extra? Что я должен делать? Again, many thanks - person Hummus; 11.12.2013
comment
@AndroidNewbie post your layout xml id of listview should be in your fragment xml - person Raghunandan; 11.12.2013
comment
are you extending Fragment or ListFragment? Если вы расширяете ListFragment, вы можете использовать метод getListView() - person Blackbelt; 11.12.2013
comment
@blackbelt Я протягиваю фрагмент. - person Hummus; 11.12.2013
comment
@Raghunandan, what xml should I post exactly? I posted all the xmls - person Hummus; 11.12.2013
comment
than you can either try to retrieve your list with id android.R.id.list or change the id of your ListView. @android:id/list is mandatory only if you extend ListActivity or ListFragment - person Blackbelt; 11.12.2013
comment
@Androidnewbie проверьте мое редактирование, как предложено Blackbelt - person Raghunandan; 11.12.2013
comment
@blackbelt it seems to work now! огромное спасибо! I still don't understand what they were trying to do? what exactly was the difference? - person Hummus; 11.12.2013

Изменить это

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

to

mContactsList = (ListView) getView().findViewById(R.id.contacts_list_view);

Редактировать:

<ListView xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+idlist"

А также

 mContactsList = (ListView) getView().findViewById(R.id.list);
person Raghunandan    schedule 11.12.2013
comment
Спасибо за быстрый ответ, но он все еще не работает. I am still getting null. - person Hummus; 11.12.2013
comment
Thanks Raghunandan, I answered to blackbelt below with the reason why I can't do that - person Hummus; 11.12.2013

заменять

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

to

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

contact_list_view.xml shoud be change as follows

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

If you are trying to do getActivity().findViewById(R.id.contacts_list_view) in onCreateView, it will return null, because the View of Fragment is not created yet. Try to do that in onResume and it will return the view:

@Override
public void onResume() {
    super.onResume();
    mContactsList = (ListView) getActivity().findViewById(R.id.contacts_list_view);
 }
person Samvel Kartashyan    schedule 12.01.2016

You have to wait till the Fragment is attached to the Activity. You can do that onAttach(Activity) in your Fragment class

person Christopher Francisco    schedule 11.12.2013

Fragment state will be saved in FragmentActivity, so you should overwrite onSaveInstanceState in your activity.

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    if(outState != null) {
        String FRAGMENTS_TAG = "android:support:fragments";
        outState.remove(FRAGMENTS_TAG);
    }
}
person AdamHsi    schedule 27.08.2020