getActivity().getComponentName()into Fragment Nullpointerexception

-1 android nullpointerexception android-fragments searchview

在多选项卡应用程序中,我在其中一个选项卡中添加了一个可扩展的列表视图和一个搜索视图(Tab2).我在getComponentName()上有一个错误,因为它不支持fragment.So我添加了getActivity().getComponentName().在此行上运行它时没有错误但是NullpointerException.应用程序崩溃.有任何想法吗?
以下是代码的重要部分:

public class Tab2 extends Fragment implements SearchView.OnQueryTextListener,SearchView.OnCloseListener{
private SearchView search;
private MylistAdapter listAdapter;
private ExpandableListView myList;
private ArrayList<Continent> continentList = new ArrayList<Continent>();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.tab2, container, false);
    SearchManager searchManager = (SearchManager)  getActivity().getSystemService(Context.SEARCH_SERVICE);
    search = (SearchView) getActivity().findViewById(R.id.search);
    search.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
    search.setIconifiedByDefault(false);
    search.setOnQueryTextListener(this);
    search.setOnCloseListener(this);

    displayList();
    expandAll();
    return rootView;
}



private void expandAll(){

    int count = listAdapter.getGroupCount();
    for (int i=0; i<count; i++)
    {
        myList.expandGroup(i);
    }
}

private void displayList() {

    // display the list
    loadSomeData();

    // get reference to the ExpandableListView
    myList = (ExpandableListView) getView().findViewById(R.id.expandableList);
    // create the adapter by passing your ArrayList data
    listAdapter = new MylistAdapter(getActivity(), continentList);
    // attach the adapter to the list
    myList.setAdapter(listAdapter);

}
Run Code Online (Sandbox Code Playgroud)

和活动:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<SearchView
    android:id="@+id/search"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true" />

<ExpandableListView
    android:id="@+id/expandableList"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/search" >
</ExpandableListView>
Run Code Online (Sandbox Code Playgroud)

Sau*_*are 5

在Fragment生命周期中,可以在创建Activity之后调用getActivity().在onActivityCreated之后,getActivity将可用.

您不能在onCreateView代码中使用getActivity.