为什么我的Fragment没有实例化?对碎片通信的活动

时间:2016-07-15 09:28:04

标签: android android-studio android-fragments android-fragmentactivity

我正在尝试从我的Activity(从Firebase获取数据)向另一个片段发送数据。仅当我在创建活动时更改Firebase上的数据而不是第一次尝试时,它才有效。在第一次尝试时,方法passDataToInfoFragment和passDataToRanklistFragment中的片段始终为NULL。我不知道为什么,所以我需要你的帮助。

GroupDetailFragmentCommunication:

public interface GroupDetailFragmentCommunication {
    public void passDataToInfoFragment(PublicGroup group);
    public void passDataToRanklistFragment(PublicGroup group);
}

GroupDetailActivity:

public class GroupDetailActivity extends AppCompatActivity implements GroupDetailFragmentCommunication{

    private FirebaseAuth auth;
    private FirebaseDatabase database;
    private DatabaseReference reference;
    private GroupDetailPagerAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_detail);
        this.initFirebase();
        this.setUpToolbar();
        this.setUpTabLayout();
        this.getPublicGroup();
    }

    public void initFirebase() {
        auth = FirebaseAuth.getInstance();
        database = FirebaseDatabase.getInstance();
        reference = database.getReference();
    }

    public void setUpToolbar() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("Details");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    public void setUpTabLayout() {
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        ArrayList<String> tabs = new ArrayList<>();
        tabs.add("Info");
        tabs.add("Rank");

        final ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
        this.adapter = new GroupDetailPagerAdapter(getSupportFragmentManager(), tabs);
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);
    }

    public void getPublicGroup() {
            reference.child("groups").child("public").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
                PublicGroup pg = snapshot.getValue(PublicGroup.class);
                if (pg != null) {
                    pg.setKey(snapshot.getKey());
                    passDataToInfoFragment(pg);
                    passDataToRanklistFragment(pg);
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
            
            }
        });
    }


     @Override
    public void passDataToInfoFragment(PublicGroup group) {
        InfoFragment fragment = (InfoFragment) this.adapter.getFragment(0);
        if (fragment != null) {
            fragment.fragmentCommunication(group);
        } else {
            Log.i("Bla", "Fragment 1 is not instantiated");
        }
    }
s
    @Override
    public void passDataToRanklistFragment(PublicGroup group) {
        RanklistFragment fragment = (RanklistFragment) this.adapter.getFragment(1);
        if (fragment != null) {
            fragment.fragmentCommunication(group);
        } else {
            Log.i("Bla", "Fragment 2 is not instantiated");
        }
    }


}

GroupDetailPagerAdapter:

public class GroupDetailPagerAdapter extends FragmentStatePagerAdapter {
    private SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
    private ArrayList<String> tabHeader;

    public GroupDetailPagerAdapter(FragmentManager fm, ArrayList<String> tabHeader) {
        super(fm);
        this.tabHeader = tabHeader;
    }

    @Override
    public Fragment getItem(int position) {

        switch (position) {
            case 0:
                Fragment infoTab = new InfoFragment();
                return infoTab;
            case 1:
                Fragment ranklistTab = new RanklistFragment();
                return ranklistTab;
            default:
                return null;
        }
    }

    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Fragment fragment = (Fragment) super.instantiateItem(container, position);
        registeredFragments.put(position, fragment);
        return fragment;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        registeredFragments.remove(position);
        super.destroyItem(container, position, object);
    }

    public Fragment getFragment(int position) {
        return registeredFragments.get(position);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return tabHeader.get(position);
    }
}

2 个答案:

答案 0 :(得分:1)

快速浏览一下代码后,我有一些怀疑:

  • 您是否尝试过设置断点 getPublicGroup() - &gt; onDataChange(DataSnapshot快照)方法?如果 pg 为null,则不会调用&#34;传递&#34; -methods。

如果不是这种情况,那么当您在 onCreate()中调用 this.getPublicGroup()时,可能会出现未完全实例化片段的情况。父母活动。

  • 您可以尝试将此行移至父活动的 onResume()方法,这有用吗?

答案 1 :(得分:0)

要从适配器获取片段实例,请调用instantiateItem而不是getFragment(在passData ...方法中)。

如果调用instantiateItem,则会获得适配器引用的片段。不要担心多次调用instantiateItem,如果已经实例化,则只需要返回一个引用。

不要在适配器中维护自己对片段的引用,因为适配器可以更换这些片段而不更新这些引用。