gpt4 book ai didi

android - fragment 监听器上的 NullPointerException

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:39:20 27 4
gpt4 key购买 nike

我有一个带有 ViewPager 的 Activity,在 ViewPager Adapter 中,我为每个位置提供了 Fragment。

一个示例 Fragment 是 DebugFragment。我已经在下面编写了源代码。

public class DebugFragment extends android.support.v4.app.Fragment {

private OnFragmentInteractionListener mListener;

public interface OnFragmentInteractionListener {
void onFragmentInteraction(int someValue);
}

public static DebugFragment newInstance() {
DebugFragment fragment = new DebugFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
mListener.onFragmentInteraction(0);
}
};

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LocalBroadcastManager.getInstance(getContext()).registerReceiver(mMessageReceiver,
new IntentFilter("com.android.example.INITIAL_REQUEST"));
}

@Override
public void onDestroy() {
LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}

@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}

@Override
public void onDetach() {
super.onDetach();
mListener = null;
}

@Override
public void onResume() {
super.onResume();
getUserData();
}

public void getUserData() {
// Inside Background Thread
if (getActivity() == null) {
return;
}
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
mListener.onFragmentInteraction(0); // This line throws NPE
}
});
}

下面是我的 Activity 实现。

public class DebugActivity extends AppCompatActivity implements
DebugFragment.OnFragmentInteractionListener {

// Other Activity Callback

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
DebugFragment debugFragment = ((DebugFragment) mViewPagerAdapter.getRegisteredFragment(2));
if (debugFragment != null) {
debugFragment.getUserData();
}
}
}
}
}

我从 Fragment 的 onResume、BroadcastReceiver、Activity 的 OnActivityResult 调用我的 DebugFragment 的 getUserData。

有时我在尝试访问 FragmentListener 即 mListener 时在 getUserData 中得到 NullPointerException。我想知道为什么?

因为我已经在检查 Activity 是否为 null。这还不够吗。我还必须检查 mListener 的空值吗?如果有人会向我解释 Activity 不会为空但我的 mListener 将为空的情况,那就太好了。我只将我的 Activity 保持在纵向模式。

编辑

我的适配器代码

public abstract class TabPagerAdapter extends FragmentPagerAdapter {

public TabPagerAdapter(FragmentManager fm) {
super(fm);
}

public abstract View getTabView(int position);
}

public class SecondaryPagerAdapter extends TabPagerAdapter {

private static final int NUM_PAGES = 5;

private String tabTitles[] = new String[] { "Today", "New", "Calendar", "In-progress", "Invoices" };
private int[] imageResId = { R.drawable.ic_tab_hired_pro, R.drawable.ic_tab_history,
R.drawable.ic_tab_today, R.drawable.ic_tab_inprogress, R.drawable.ic_tab_invoices };
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();

public SecondaryPagerAdapter(FragmentManager fm) {
super(fm);
}

@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
case 1:
case 3:
return ServiceRequestFragment.newInstance(tabTitles[position]);
case 2:
return DebugFragment.newInstance();
case 4:
return InvoicesFragment.newInstance();
default:
throw new RuntimeException("No fragment for this position");
}
}

@Override
public int getCount() {
return NUM_PAGES;
}

@Override
public View getTabView(int position) {
CustomTab customTab = new CustomTab(DashBoardActivity.this);
customTab.bindWith(imageResId[position], tabTitles[position]);
return customTab;
}

@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 getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}

在我的 Activity 中,我这样调用它

mSecondaryPagerAdapter = new SecondaryPagerAdapter(getSupportFragmentManager());
mSecondaryPager = (ViewPager) findViewById(R.id.dashboard_pager);
mSecondaryPager.setOffscreenPageLimit(4);
mSecondaryPager.setAdapter(mSecondaryPagerAdapter);

最佳答案

当您调用 getActivity().runOnUiThread(new Runnable() {}) 时,这会将 Runnable 排入队列以在 UI 线程上运行之后所有其他已经存在的线程在 UI 线程上排队,这可能包括对 onDestroy() 的调用,这会将 mListener 设置为 null。这意味着您的应用程序可能会在广播进入时关闭。虽然在正常情况下这应该不是问题,因为您在清除 mListener 之前注销了接收器,但有可能在此之后Runnable已经入队,这就是监听器执行时为null的原因。

为避免 NPE,您应该检查 Runnable 中的 mListener == null。但是,这仍然意味着回调是在您的 Fragment 被销毁之后安排的,因此,您的 Fragment 实例被泄露了。最好的办法是创建一个 Handler 并将 Runnable 发送给它,而不是调用 runOnUiThread()。然后,在 onDestroy() 中,调用 mHandler.removeCallbacksAndMessages(null),这实际上清除了队列,因此根本不会调用 Runnable。

关于android - fragment 监听器上的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37117468/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com