Android-getSupportFragmentManager()返回null [英] Android - getSupportFragmentManager() returning null

查看:154
本文介绍了Android-getSupportFragmentManager()返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这里有很多类似的问题,但是到目前为止,这些问题都没有为我解决,所以我希望通过在这里发布我的(略有删节的)课程,有人可以帮助我.这是一个ViewPager,使用4个片段作为页面.

所以我的问题是方法getFragmentByPosition无法正常工作,因为getSupportFragmentManager()返回null.在我的onCreate上,如果我尝试从中调用任何内容,mSectionsPagerAdapter也会返回null,但是我的选项卡都显示的很好,而且我无法从所需的片段中访问数据.

我现在真的不知道问题出在什么地方,因此我们将不胜感激.我之前发布了其他一些问题,并尝试了无济于事的建议,因此现在我只发布了我的整个课程.谢谢!

  package com.me.testapp;导入java.text.SimpleDateFormat;导入java.util.Date;导入java.util.Locale;导入android.net.Uri;导入android.support.v4.app.FragmentActivity;导入android.support.v7.app.ActionBarActivity;导入android.support.v4.app.Fragment;导入android.support.v4.app.FragmentManager;导入android.support.v4.app.FragmentPagerAdapter;导入android.os.Bundle;导入android.support.v4.view.ViewPager;导入android.support.v7.app.AppCompatActivity;导入android.support.v7.widget.Toolbar;导入android.view.Menu;导入android.view.MenuItem;导入android.view.View;导入android.widget.CheckBox;导入android.widget.TextView;导入com.me.testapp.CheckListFragments.Thing1Fragment;导入com.me.testapp.CheckListFragments.Thing2Fragment;导入com.me.testapp.CheckListFragments.Thing3Fragment;导入com.me.testapp.CheckListFragments.Thing4Fragment;导入com.me.testapp.Data.ClientDAO;导入io.karim.MaterialTabs;公共类CheckList扩展AppCompatActivity实现Thing1Fragment.OnFragmentInteractionListener,Thing2Fragment.OnFragmentInteractionListener,Thing3Fragment.OnFragmentInteractionListener,Thing4Fragment.OnFragmentInteractionListener {/*** {@link android.support.v4.view.PagerAdapter}将提供*每个部分的片段.我们使用* {@link FragmentPagerAdapter}派生版本,它将保留每个*在内存中加载片段.如果这变得太占用内存,它会*最好切换到* {@link android.support.v4.app.FragmentStatePagerAdapter}.*//***将托管部分内容的{@link ViewPager}.*/公共SectionsPagerAdapter mSectionsPagerAdapter;公共ViewPager寻呼机;私人ClientDAO clientDAO;@Override公共无效onCreate(捆绑保存的InstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_checklist);工具栏工具栏=(工具栏)findViewById(R.id.toolbar);setSupportActionBar(toolbar);TextView工具栏名称=(TextView)findViewById(R.id.toolbar_name);TextViewtoolbarFloor =(TextView)findViewById(R.id.toolbar_floor);TextView工具栏Office =(TextView)findViewById(R.id.toolbar_office);toolbarName.setText(getIntent().getStringExtra("Name")));toolbarRoom.setText(:" + getIntent().getStringExtra("Office"));toolbarFloor.setVisibility(View.GONE);//初始化ViewPager并设置适配器传呼器=(ViewPager)findViewById(R.id.pager);mSectionsPagerAdapter = new SectionsPagerAdapter(this.getSupportFragmentManager());pager.setAdapter(mSectionsPagerAdapter);pager.setOffscreenPageLimit(3);//将标签页绑定到ViewPagerMaterialTabs标签=(MaterialTabs)findViewById(R.id.tabs);tabs.setViewPager(pager);clientDAO =新的ClientDAO(getApplicationContext());}@Overridepublic boolean onCreateOptionsMenu(Menu menu){//膨胀菜单;这会将项目添加到操作栏(如果有).getMenuInflater().inflate(R.menu.menu_checklist,menu);返回true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item){//单击操作栏项.动作栏将//自动处理主页"/向上"按钮上的点击,//当您在AndroidManifest.xml中指定父活动时.int id = item.getItemId();//noinspection SimplifiableIfStatement如果(id == R.id.action_settings){返回true;}返回super.onOptionsItemSelected(item);}/*** {@link FragmentPagerAdapter}返回与以下内容相对应的片段*部分/标签/页面之一.*/公共类SectionsPagerAdapter扩展FragmentPagerAdapter {公共SectionsPagerAdapter(FragmentManager fm){超级(fm);}@Overridepublic Fragment getItem(int position){//调用getItem实例化给定页面的片段.//返回一个PlaceholderFragment(在下面定义为静态内部类).开关(位置){案例0:Thing1Fragment Thing1 =新的Thing1Fragment();返回thing1;情况1:Thing2Fragment Thing2 =新的Thing2Fragment();返回thing2;情况2:Thing3Fragment Thing3 =新的Thing3Fragment();返回thing3;情况3:Thing4Fragment Thing4 =新的Thing4Fragment();返回thing4;默认:Thing1 =新的Thing1Fragment();返回thing1;}}@Overridepublic int getCount(){//显示总共4页.返回4;}@Override公共CharSequence getPageTitle(int position){语言环境l = Locale.getDefault();开关(位置){案例0:返回getString(R.string.title_section1).toUpperCase(l);情况1:返回getString(R.string.title_section2).toUpperCase(l);情况2:返回getString(R.string.title_section3).toUpperCase(l);情况3:返回getString(R.string.title_section4).toUpperCase(l);}返回null;}}public void onFragmentInteraction(Uri uri){//您可以将其留空}public int booleanToInt(boolean bool){返回布尔?1:0;}公共片段getFragmentByPosition(int pos){字符串标签="android:switcher:" + R.id.pager +:" + pos;返回getSupportFragmentManager().findFragmentByTag(tag);}public int getCheckboxState(int id,String page){开关(页面){案例"thing1":return booleanToInt((((CheckBox)getFragmentByPosition(0).getView().findViewById(id)).isChecked());案例"thing2":return booleanToInt((((CheckBox)getFragmentByPosition(1).getView().findViewById(id)).isChecked());案例"thing3":return booleanToInt((((CheckBox)getFragmentByPosition(2).getView().findViewById(id)).isChecked());案例"thing4":return booleanToInt((((CheckBox)getFragmentByPosition(3).getView().findViewById(id)).isChecked());默认:return booleanToInt((((CheckBox)getFragmentByPosition(0).getView().findViewById(id)).isChecked());}}} 

解决方案

我遇到了同样的问题.

关于活动生命周期的推断,在onCreate活动的方法中并未完全创建,因此当您尝试传递 getSupportFragmentManager null 时./p>

解决该问题的方法是将这行代码放在 onStart 中.问题在于,每次暂停活动并再次运行该活动, Fragment 都会重新启动.

I know there are a lot of similar questions here, but none of them have worked for me so far, so I'm hoping by just posting my (slightly redacted) class here, someone can help me out. It's a ViewPager using 4 fragments as the pages.

So my problem is that the method getFragmentByPosition isn't working, because getSupportFragmentManager() is returning null. Up in my onCreate, mSectionsPagerAdapter is also returning null if I try to call anything from that, however my tabs all show up fine, and I'm just not able to access the data from my fragments that I need.

I really don't know what the issue is at this point, so any help is appreciated. I posted a few other questions before, and tried the suggestions to no avail, so now I'm just posting up my entire class. Thanks!

package com.me.testapp;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.net.Uri;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

import com.me.testapp.CheckListFragments.Thing1Fragment;
import com.me.testapp.CheckListFragments.Thing2Fragment;
import com.me.testapp.CheckListFragments.Thing3Fragment;
import com.me.testapp.CheckListFragments.Thing4Fragment;
import com.me.testapp.Data.ClientDAO;

import io.karim.MaterialTabs;


public class CheckList extends AppCompatActivity
        implements Thing1Fragment.OnFragmentInteractionListener,
        Thing2Fragment.OnFragmentInteractionListener,
        Thing3Fragment.OnFragmentInteractionListener,
        Thing4Fragment.OnFragmentInteractionListener {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    /**
     * The {@link ViewPager} that will host the section contents.
     */

    public SectionsPagerAdapter mSectionsPagerAdapter;
    public ViewPager pager;
    private ClientDAO clientDAO;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_checklist);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        TextView toolbarName = (TextView) findViewById(R.id.toolbar_name);
        TextView toolbarFloor = (TextView) findViewById(R.id.toolbar_floor);
        TextView toolbarOffice = (TextView) findViewById(R.id.toolbar_office);

        toolbarName.setText(getIntent().getStringExtra("Name"));
        toolbarRoom.setText(": " + getIntent().getStringExtra("Office"));

        toolbarFloor.setVisibility(View.GONE);

        // Initialize the ViewPager and set an adapter
        pager = (ViewPager) findViewById(R.id.pager);
        mSectionsPagerAdapter = new SectionsPagerAdapter(this.getSupportFragmentManager());
        pager.setAdapter(mSectionsPagerAdapter);
        pager.setOffscreenPageLimit(3);

        // Bind the tabs to the ViewPager
        MaterialTabs tabs = (MaterialTabs) findViewById(R.id.tabs);
        tabs.setViewPager(pager);

        clientDAO = new ClientDAO(getApplicationContext());

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_checklist, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {
        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            switch(position) {
                case 0:
                    Thing1Fragment thing1 = new Thing1Fragment();
                    return thing1;
                case 1:
                    Thing2Fragment thing2 = new Thing2Fragment();
                    return thing2;
                case 2:
                    Thing3Fragment thing3 = new Thing3Fragment();
                    return thing3;
                case 3:
                    Thing4Fragment thing4 = new Thing4Fragment();
                    return thing4;
                default:
                    thing1 = new Thing1Fragment();
                    return thing1;
            }
        }

        @Override
        public int getCount() {
            // Show 4 total pages.
            return 4;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
                case 0:
                    return getString(R.string.title_section1).toUpperCase(l);
                case 1:
                    return getString(R.string.title_section2).toUpperCase(l);
                case 2:
                    return getString(R.string.title_section3).toUpperCase(l);
                case 3:
                    return getString(R.string.title_section4).toUpperCase(l);
            }
            return null;
        }
    }

    public void onFragmentInteraction(Uri uri){
        //you can leave it empty
    }

    public int booleanToInt(boolean bool) {
        return bool ? 1 : 0;
    }

    public Fragment getFragmentByPosition(int pos) {
        String tag = "android:switcher:" + R.id.pager + ":" + pos;
        return getSupportFragmentManager().findFragmentByTag(tag);
    }

    public int getCheckboxState(int id, String page) {

        switch (page) {
            case "thing1":
                return booleanToInt(((CheckBox) getFragmentByPosition(0).getView().findViewById(id)).isChecked());
            case "thing2":
                return booleanToInt(((CheckBox) getFragmentByPosition(1).getView().findViewById(id)).isChecked());
            case "thing3":
                return booleanToInt(((CheckBox) getFragmentByPosition(2).getView().findViewById(id)).isChecked());
            case "thing4":
                return booleanToInt(((CheckBox) getFragmentByPosition(3).getView().findViewById(id)).isChecked());
            default:
                return booleanToInt(((CheckBox) getFragmentByPosition(0).getView().findViewById(id)).isChecked());
        }
    }
}

解决方案

I was having the same problem.

What I deduce it about the lifecycle of the activity, in the method onCreate the activity isn't totally created so when you try to pass getSupportFragmentManager its null.

What I do to resolve it, is putting this lines of code in onStart. The problem there is that each time the activity is paused and run it again the Fragment will be restarting.

这篇关于Android-getSupportFragmentManager()返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆