[从活动中访问片段时,Android稀有NPE

问题描述 投票:0回答:1

我在Android中有一个包含框架布局的活动。框架布局之一是用片段填充的。在片段的onResume()中,调用了在Activity中实现的侦听器。侦听器然后调用该片段的方法。此时,在对片段的引用上会出现一个NPE。

它很少发生,但已被复制至少2次。我怀疑问题与活动和片段的生命周期有关。当活动仍处于生命周期的onCreate()步骤中时(可能是在初始化片段之前),将对该片段进行引用。

我的分析正确吗?如何预防NPE?

这里是代码(请记住,我已经重命名了很多代码,并删除了似乎无关的部分:):

活动:

FoodsActivity extends AppCompatActivity implements FruitStateFragment.OnAppleSelectedListener {

    private Context mContext;
    private FruitsManager mFruitsManagr;
    private FruitStateFragment mFruitStateFragment;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.foods_activity);

        if (savedInstanceState != null) {
            return;
        }

        if (mContext == null) {
            mContext = getApplicationContext();
        }
        mFruitsManagr = FruitsManager.get(mContext);

        if (findViewById(R.id.fl_fruits_status) != null) {
            mFruitStateFragment = new FruitStateFragment();
            mFruitStateFragment.setArguments(getIntent().getExtras());
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fl_fruits_status, mFruitStateFragment, "FruitStateFragment").commit();
        }

        mFruitsManagr.setApple(0);
    }

    @Override
    public void onAttachFragment(Fragment fragment) {
        if (fragment instanceof FruitStateFragment) {
            FruitStateFragment fruitStateFragment = (FruitStateFragment) fragment;
            fruitStateFragment.setOnSimNumSelectedListener(this);
        }
    }

    public void onAppleSelected(Integer appleNum) {
        FruitsManager fManager = FruitsManager.get(mContext);
        fManager.setApple(appleNum);
        // NPE on mFruitStateFragment
        mFruitStateFragment.updateBasketUi(fManager.getActiveBasketName());
    }   
}

片段:

FruitStateFragment extends Fragment {

    private Context mContext;

    FruitsManager mFruitsManagr;
    OnAppleSelectedListener mAppleCallback;

    public void setOnAppleSelectedListener(OnAppleSelectedListener callback) {
        this.mAppleCallback = callback;
    }

    public interface OnAppleSelectedListener {
        void onAppleSelected(Integer appleNum);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (mContext == null) {
            mContext = getActivity().getApplicationContext();
        }
        mFruitsManagr = FruitsManager.get(mContext);
    }

    @Override
    public void onResume() {
        super.onResume();
        mAppleCallback.onAppleSelected(mFruitsManagr.getActiveApple());
    }

    void updateBasketUi(String basketName) {
    }

}

经理:

public class FruitsManager {

    private static FruitsManager sMe;
    private Context mContext;

    private static int mActiveApple = 0;
    private static String mActiveBasketName = "";

    private FruitsManager(Context context) {
        mContext = context;
        initInterfaces();
    }

    public int getActiveApple() {
        return mActiveApple;
    }

    public int getActiveBasketName() {
        return mActiveBasketName;
    }

}

日志:

D FRUITS: 0001 onCreate (FoodsActivity%onCreate:)
D FRUITS: 0002 onCreate (FruitStateFragment%onCreate:)
D FRUITS: 0003 onCreateView (FruitStateFragment%onCreateView:)
D FRUITS: 0004 onActivityCreated (FruitStateFragment%onActivityCreated:)
D FRUITS: 0005 initViews (FruitStateFragment%initViews:)
D FRUITS: 0006 onResume (FruitStateFragment%onResume:)
E AndroidRuntime: java.lang.RuntimeException: Unable to resume activity {com.hi/FoodsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.hi.FruitStateFragment.updateBasketUi(java.lang.String)' on a null object reference
android android-fragments android-activity listener activity-lifecycle
1个回答
0
投票

这些行:

if (savedInstanceState != null) {
    return;
}

表示您没有在重新创建活动时设置mFruitStateFragment变量-仅在首次添加片段时才进行设置。这也意味着您的mFruitsManagrmContext也未设置,因为它也在该行之后。如果您希望每次创建活动时都可以使用这些功能,则应删除该检查并只包装应该只发生一次的内容。

这意味着您的活动应改为

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.foods_activity);

    if (mContext == null) {
        mContext = getApplicationContext();
    }
    mFruitsManagr = FruitsManager.get(mContext);

    if (savedInstanceState == null) {
        mFruitStateFragment = new FruitStateFragment();
        mFruitStateFragment.setArguments(getIntent().getExtras());
        getSupportFragmentManager().beginTransaction()
                .add(R.id.fl_fruits_status, mFruitStateFragment, "FruitStateFragment").commit();
        // I assume this shouldn't be set every time the activity
        // is recreated
        mFruitsManagr.setApple(0);
    } else {
        // Get the Fragment that is already created from the FragmentManager
        mFruitStateFragment = getSupportFragmentManager()
            .findFragmentById(R.id.fl_fruits_status);
    }
}

当然,由于您使用的是onAttachFragment(),因此您还可以从那里获得一个引用,因为在您每次重新创建活动时都会调用该引用:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.foods_activity);

    if (mContext == null) {
        mContext = getApplicationContext();
    }
    mFruitsManagr = FruitsManager.get(mContext);

    if (savedInstanceState == null) {
        // We'll store a reference to this in onAttachFragment()
        FruitStateFragment fruitStateFragment = new FruitStateFragment();
        fruitStateFragment.setArguments(getIntent().getExtras());
        getSupportFragmentManager().beginTransaction()
                .add(R.id.fl_fruits_status, fruitStateFragment, "FruitStateFragment").commit();
        // I assume this shouldn't be set every time the activity
        // is recreated
        mFruitsManagr.setApple(0);
    }
}

@Override
public void onAttachFragment(Fragment fragment) {
    if (fragment instanceof FruitStateFragment) {
        // This get called every time the activity is created,
        // ensuring that mFruitStateFragment is always set
        mFruitStateFragment = (FruitStateFragment) fragment;
        mFruitStateFragment.setOnSimNumSelectedListener(this);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.