Android findFragmentById 返回 null

Posted

技术标签:

【中文标题】Android findFragmentById 返回 null【英文标题】:Android findFragmentById returns null 【发布时间】:2013-06-27 22:53:49 【问题描述】:

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

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

ListFragment 尚未创建,但我需要将它与其他的一样放入片段数组中。我该怎么办?

活动

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
    

编辑

活动 xml

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

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

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

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

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

</LinearLayout>

【问题讨论】:

哪一行代码是MainActivity.java:154 fragments[FAVORITES].getView().findViewById(R.id.favoritesFragment); 【参考方案1】:

你不见了fragments[FAVORITES] = fm.findFragmentById(R.id.favoritesFragment)

【讨论】:

我知道,但它是在活动 xml 中声明的。我怎样才能得到它? 为什么不在执行fragments[FAVORITES].getView() 之前插入@tony 指示的行。 fragments[FAVORITES] 在初始化之前为空。 呃对不起@tony !!!现在我明白了,我绝对确定我已经写了...但是现在我有这个例外Caused by: android.support.v4.app.SuperNotCalledException: Fragment FavoritesFragment415dc380 #6 id=0x7f05002b did not call through to super.onActivityCreated() 是的!刚刚添加了超级方法 onActivityCreated。非常感谢你们! @HeatfanJohn

以上是关于Android findFragmentById 返回 null的主要内容,如果未能解决你的问题,请参考以下文章

getSupportFragmentManager().findFragmentById 为 android 片段中的谷歌地图返回 null?

SupportMapFragment 的 findFragmentById 在 Android Studio 中返回 null

Mapfragment findFragmentById 始终为空

findFragmentById() 和 findFragmentByTag()

为啥 findFragmentById 总是返回 null

迁移到 AndroidX 后,findFragmentById 为片段返回 null