Android findFragmentById 返回 null

标签 android nullpointerexception fragment findviewbyid

我有一个管理 fragment 列表的 Activity 。其中之一是 ListFragment,当 Activity 试图在 Create() 期间找到它时,我得到一个 Null 异常。

Caused by: java.lang.NullPointerException
at com.example.foodexp01b.MainActivity.onCreate(MainActivity.java:154)

ListFragment 尚未创建,但我需要将其放入 fragment 数组中。我该怎么办?

Activity

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        uiHelper = new UiLifecycleHelper(this, callback);
        uiHelper.onCreate(savedInstanceState);

        FragmentManager fm = getSupportFragmentManager();
        fragments[LOGIN] = fm.findFragmentById(R.id.loginFragment);
        fragments[HOME] = fm.findFragmentById(R.id.homeFragment);
        fragments[SETTINGS] = fm.findFragmentById(R.id.settingsFragment);
        fragments[SETTINGS].getView().findViewById(R.id.back_button1)
        .setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                currentFragment = HOME;
                showFragment(HOME, false);
            }
        });
        fragments[DESTINATIONS] = fm.findFragmentById(R.id.destinationFragment);
        fragments[DESTINATIONS].getView().findViewById(R.id.back_button2)
        .setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                currentFragment = HOME;
                showFragment(HOME, false);
            }
        });
        fragments[MAP] = fm.findFragmentById(R.id.mapFragment);
        fragments[RESTAURANT] = fm.findFragmentById(R.id.restaurantFragment);
        fragments[RESTAURANT].getView().findViewById(R.id.restaurant_back_button)
        .setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                currentFragment = MAP;
                showFragment(MAP, false);
            }
        });
        fragments[FAVORITES].getView().findViewById(R.id.favoritesFragment);
        FragmentTransaction transaction = fm.beginTransaction();
        for(int i = 0; i < fragments.length; i++) {
            transaction.hide(fragments[i]);
        }
        transaction.commit();
    }

ListFragment代码

public class FavoritesFragment extends ListFragment{

    private ListView listView;
    private List<BaseListElement> listElements;

    OnFavoritesFragmentListener mCallback;

    ArrayList<String> favorites;

    // Container Activity must implement this interface
    public interface OnFavoritesFragmentListener {
        public void onSearchSelected();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallback = (OnFavoritesFragmentListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFavoritesFragmentListener");
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState){
        favorites = new ArrayList<String>();
        setListAdapter(new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, favorites));
    }
    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        //do something
    }
}

编辑

Activity xml

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

    <fragment android:name="com.example.foodexp01b.HomeFragment"
          android:id="@+id/homeFragment"
          android:layout_width="match_parent"
          android:layout_height="match_parent" />
    <fragment android:name="com.example.foodexp01b.LoginFragment"
          android:id="@+id/loginFragment"
          android:layout_width="match_parent"
          android:layout_height="match_parent" />
    <fragment android:name="com.example.foodexp01b.SettingsFragment"
          android:id="@+id/settingsFragment"
          android:layout_width="match_parent"
          android:layout_height="match_parent" />

    <fragment android:name="com.example.foodexp01b.DestinationFragment"
          android:id="@+id/destinationFragment"
          android:layout_width="match_parent"
          android:layout_height="match_parent" />
    <fragment
          android:id="@+id/mapFragment"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:name="com.google.android.gms.maps.SupportMapFragment"/>

    <fragment android:name="com.example.foodexp01b.RestaurantFragment"
          android:id="@+id/restaurantFragment"
          android:layout_width="match_parent"
          android:layout_height="match_parent" />

    <fragment android:name="com.example.foodexp01b.FavoritesFragment"
          android:id="@+id/favoritesFragment"
          android:layout_width="match_parent"
          android:layout_height="match_parent" />

</LinearLayout>

最佳答案

您缺少 fragments[FAVORITES] = fm.findFragmentById(R.id.favoritesFragment)

关于Android findFragmentById 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17393965/

相关文章:

java - 使用Interface从Fragment调用值到Activity引起ClassCastException

android - 带有错误 :Cause: tried to access method 的 Gradle 构建

java,字符串方法如果参数为null,则应返回null,但会抛出NullPointerException

java - 如何在 mainActivity 布局的工具栏中删除这个箭头?

java - 如何从 .jar Android 加载类

java - 声明 Java 对象数组的数组时遇到问题

Android - 关于 fragment

android - 如何设置 Mockito 模拟 Android 单元测试类

android - 如何避免在 Activity 中使用相同样式的对话框?

安卓;如何在不使用 ksoap 的情况下调用 SOAP Web 服务?