197

在开发人员控制台错误报告中,有时我会看到带有 NPE 问题的报告。我不明白我的代码有什么问题。在模拟器上,我的设备应用程序在没有强制关闭的情况下运行良好,但是当调用 getActivity() 方法时,一些用户在片段类中得到 NullPointerException。

活动

pulic class MyActivity extends FragmentActivity{

    private ViewPager pager; 
    private TitlePageIndicator indicator;
    private TabsAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        pager = (ViewPager) findViewById(R.id.pager);
        indicator = (TitlePageIndicator) findViewById(R.id.indicator);
        adapter = new TabsAdapter(getSupportFragmentManager(), false);

        adapter.addFragment(new FirstFragment());
        adapter.addFragment(new SecondFragment());
        indicator.notifyDataSetChanged();
        adapter.notifyDataSetChanged();

        // push first task
        FirstTask firstTask = new FirstTask(MyActivity.this);
        // set first fragment as listener
        firstTask.setTaskListener((TaskListener) adapter.getItem(0));
        firstTask.execute();
    }

    indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener()  {
        @Override
        public void onPageSelected(int position) {
            Fragment currentFragment = adapter.getItem(position);
            ((Taskable) currentFragment).executeTask();
        }

        @Override
        public void onPageScrolled(int i, float v, int i1) {}

        @Override
        public void onPageScrollStateChanged(int i) {}
    });
}

异步任务类

public class FirstTask extends AsyncTask{

    private TaskListener taskListener;

    ...

    @Override
    protected void onPostExecute(T result) {
        ... 
        taskListener.onTaskComplete(result);
    }   
}

片段类

public class FirstFragment extends Fragment immplements Taskable, TaskListener{

    public FirstFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.first_view, container, false);
    }

    @Override
    public void executeTask() {
        FirstTask firstTask = new FirstTask(MyActivity.this);
        firstTask.setTaskListener(this);
        firstTask.execute();
    }

    @Override
    public void onTaskComplete(T result) {
        // NPE is here 
        Resources res = getActivity().getResources();
        ...
    }
}

当应用程序从后台恢复时,可能会发生此错误。在这种情况下,我应该如何正确处理这种情况?

4

8 回答 8

125

看来我找到了解决问题的方法。这里这里给出了很好的解释。这是我的例子:

pulic class MyActivity extends FragmentActivity{

private ViewPager pager; 
private TitlePageIndicator indicator;
private TabsAdapter adapter;
private Bundle savedInstanceState;

 @Override
public void onCreate(Bundle savedInstanceState) {

    .... 
    this.savedInstanceState = savedInstanceState;
    pager = (ViewPager) findViewById(R.id.pager);;
    indicator = (TitlePageIndicator) findViewById(R.id.indicator);
    adapter = new TabsAdapter(getSupportFragmentManager(), false);

    if (savedInstanceState == null){    
        adapter.addFragment(new FirstFragment());
        adapter.addFragment(new SecondFragment());
    }else{
        Integer  count  = savedInstanceState.getInt("tabsCount");
        String[] titles = savedInstanceState.getStringArray("titles");
        for (int i = 0; i < count; i++){
            adapter.addFragment(getFragment(i), titles[i]);
        }
    }


    indicator.notifyDataSetChanged();
    adapter.notifyDataSetChanged();

    // push first task
    FirstTask firstTask = new FirstTask(MyActivity.this);
    // set first fragment as listener
    firstTask.setTaskListener((TaskListener) getFragment(0));
    firstTask.execute();

}

private Fragment getFragment(int position){
     return savedInstanceState == null ? adapter.getItem(position) : getSupportFragmentManager().findFragmentByTag(getFragmentTag(position));
}

private String getFragmentTag(int position) {
    return "android:switcher:" + R.id.pager + ":" + position;
}

 @Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("tabsCount",      adapter.getCount());
    outState.putStringArray("titles", adapter.getTitles().toArray(new String[0]));
}

 indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            Fragment currentFragment = adapter.getItem(position);
            ((Taskable) currentFragment).executeTask();
        }

        @Override
        public void onPageScrolled(int i, float v, int i1) {}

        @Override
        public void onPageScrollStateChanged(int i) {}
 });

这段代码的主要思想是,在正常运行应用程序时,您会创建新片段并将它们传递给适配器。当您恢复应用程序片段管理器时,您已经拥有该片段的实例,您需要从片段管理器获取它并将其传递给适配器。

更新

此外,在调用 getActivity() 之前使用片段检查 isAdded 是一个很好的做法。当片段与活动分离时,这有助于避免空指针异常。例如,一个活动可能包含一个推送异步任务的片段。任务完成后,将调用 onTaskComplete 侦听器。

@Override
public void onTaskComplete(List<Feed> result) {

    progress.setVisibility(View.GONE);
    progress.setIndeterminate(false);
    list.setVisibility(View.VISIBLE);

    if (isAdded()) {

        adapter = new FeedAdapter(getActivity(), R.layout.feed_item, result);
        list.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

}

如果我们打开fragment,push一个task,然后快速按回返回上一个activity,当task完成后,它会通过调用getActivity()方法尝试访问onPostExecute()中的activity。如果活动已经分离并且此检查不存在:

if (isAdded()) 

然后应用程序崩溃。

于 2012-10-17T17:57:04.523 回答
19

摆脱这种情况的最好方法是在onAttach调用时保留活动引用并在需要时使用活动引用,例如

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    mContext = context;
}

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

已编辑,因为onAttach(Activity)已折旧,现在onAttach(Context)正在使用

于 2013-08-06T11:05:10.030 回答
19

好的,我知道这个问题实际上已经解决了,但我决定分享我的解决方案。我为我创建了抽象父类Fragment

public abstract class ABaseFragment extends Fragment{

    protected IActivityEnabledListener aeListener;

    protected interface IActivityEnabledListener{
        void onActivityEnabled(FragmentActivity activity);
    }

    protected void getAvailableActivity(IActivityEnabledListener listener){
        if (getActivity() == null){
            aeListener = listener;

        } else {
            listener.onActivityEnabled(getActivity());
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        if (aeListener != null){
            aeListener.onActivityEnabled((FragmentActivity) activity);
            aeListener = null;
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        if (aeListener != null){
            aeListener.onActivityEnabled((FragmentActivity) context);
            aeListener = null;
        }
    }
}

如您所见,我添加了一个侦听器,因此,每当我需要 getFragments Activity而不是 standardgetActivity()时,我都需要调用

 getAvailableActivity(new IActivityEnabledListener() {
        @Override
        public void onActivityEnabled(FragmentActivity activity) {
            // Do manipulations with your activity
        }
    });
于 2015-09-24T09:16:40.007 回答
10

在父 Activity 中的 onStart 之前,不要调用 Fragment 中需要 getActivity() 的方法。

private MyFragment myFragment;


public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    myFragment = new MyFragment();

    ft.add(android.R.id.content, youtubeListFragment).commit();

    //Other init calls
    //...
}


@Override
public void onStart()
{
    super.onStart();

    //Call your Fragment functions that uses getActivity()
    myFragment.onPageSelected();
}
于 2015-07-14T16:12:20.413 回答
5

我一直在与这种问题作斗争一段时间,我想我已经想出了一个可靠的解决方案。

很难确定它this.getActivity()不会返回nulla Fragment,特别是如果您正在处理任何类型的网络行为,这让您的代码有足够的时间来撤回Activity引用。

在下面的解决方案中,我声明了一个名为ActivityBuffer. 本质上,这class涉及维护对拥有的可靠引用Activity,并承诺只要有有效的引用可用,就会Runnable在有效的上下文中执行 s 。Activity如果Runnables 可用,则立即安排在 UI 线程上Context执行,否则将延迟执行,直到Context准备好。

/** A class which maintains a list of transactions to occur when Context becomes available. */
public final class ActivityBuffer {

    /** A class which defines operations to execute once there's an available Context. */
    public interface IRunnable {
        /** Executes when there's an available Context. Ideally, will it operate immediately. */
        void run(final Activity pActivity);
    }

    /* Member Variables. */
    private       Activity        mActivity;
    private final List<IRunnable> mRunnables;

    /** Constructor. */
    public ActivityBuffer() {
        // Initialize Member Variables.
        this.mActivity  = null;
        this.mRunnables = new ArrayList<IRunnable>();
    }

    /** Executes the Runnable if there's an available Context. Otherwise, defers execution until it becomes available. */
    public final void safely(final IRunnable pRunnable) {
        // Synchronize along the current instance.
        synchronized(this) {
            // Do we have a context available?
            if(this.isContextAvailable()) {
                // Fetch the Activity.
                final Activity lActivity = this.getActivity();
                // Execute the Runnable along the Activity.
                lActivity.runOnUiThread(new Runnable() { @Override public final void run() { pRunnable.run(lActivity); } });
            }
            else {
                // Buffer the Runnable so that it's ready to receive a valid reference.
                this.getRunnables().add(pRunnable);
            }
        }
    }

    /** Called to inform the ActivityBuffer that there's an available Activity reference. */
    public final void onContextGained(final Activity pActivity) {
        // Synchronize along ourself.
        synchronized(this) {
            // Update the Activity reference.
            this.setActivity(pActivity);
            // Are there any Runnables awaiting execution?
            if(!this.getRunnables().isEmpty()) {
                // Iterate the Runnables.
                for(final IRunnable lRunnable : this.getRunnables()) {
                    // Execute the Runnable on the UI Thread.
                    pActivity.runOnUiThread(new Runnable() { @Override public final void run() {
                        // Execute the Runnable.
                        lRunnable.run(pActivity);
                    } });
                }
                // Empty the Runnables.
                this.getRunnables().clear();
            }
        }
    }

    /** Called to inform the ActivityBuffer that the Context has been lost. */
    public final void onContextLost() {
        // Synchronize along ourself.
        synchronized(this) {
            // Remove the Context reference.
            this.setActivity(null);
        }
    }

    /** Defines whether there's a safe Context available for the ActivityBuffer. */
    public final boolean isContextAvailable() {
        // Synchronize upon ourself.
        synchronized(this) {
            // Return the state of the Activity reference.
            return (this.getActivity() != null);
        }
    }

    /* Getters and Setters. */
    private final void setActivity(final Activity pActivity) {
        this.mActivity = pActivity;
    }

    private final Activity getActivity() {
        return this.mActivity;
    }

    private final List<IRunnable> getRunnables() {
        return this.mRunnables;
    }

}

在其实现方面,我们必须注意应用生命周期方法以与上述Pawan M描述的行为相一致:

public class BaseFragment extends Fragment {

    /* Member Variables. */
    private ActivityBuffer mActivityBuffer;

    public BaseFragment() {
        // Implement the Parent.
        super();
        // Allocate the ActivityBuffer.
        this.mActivityBuffer = new ActivityBuffer();
    }

    @Override
    public final void onAttach(final Context pContext) {
        // Handle as usual.
        super.onAttach(pContext);
        // Is the Context an Activity?
        if(pContext instanceof Activity) {
            // Cast Accordingly.
            final Activity lActivity = (Activity)pContext;
            // Inform the ActivityBuffer.
            this.getActivityBuffer().onContextGained(lActivity);
        }
    }

    @Deprecated @Override
    public final void onAttach(final Activity pActivity) {
        // Handle as usual.
        super.onAttach(pActivity);
        // Inform the ActivityBuffer.
        this.getActivityBuffer().onContextGained(pActivity);
    }

    @Override
    public final void onDetach() {
        // Handle as usual.
        super.onDetach();
        // Inform the ActivityBuffer.
        this.getActivityBuffer().onContextLost();
    }

    /* Getters. */
    public final ActivityBuffer getActivityBuffer() {
        return this.mActivityBuffer;
    }

}

最后,在您对调用不信任的任何区域中FragmentBaseFragment只需getActivity()调用this.getActivityBuffer().safely(...)并声明ActivityBuffer.IRunnable任务!

然后保证您的内容void run(final Activity pActivity)沿着 UI 线程执行。

然后ActivityBuffer可以按如下方式使用:

this.getActivityBuffer().safely(
  new ActivityBuffer.IRunnable() {
    @Override public final void run(final Activity pActivity) {
       // Do something with guaranteed Context.
    }
  }
);
于 2017-07-19T14:45:22.370 回答
3
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    // run the code making use of getActivity() from here
}
于 2016-06-14T16:04:25.340 回答
1

我知道这是一个老问题,但我认为我必须提供我的答案,因为我的问题没有被其他人解决。

首先:我正在使用 fragmentTransactions 动态添加片段。第二:我的片段是使用 AsyncTasks(服务器上的数据库查询)修改的。第三:我的片段在活动开始时未实例化第四:我使用自定义片段实例化“创建或加载它”来获取片段变量。第四:活动因方向变化而重新创建

问题是由于查询答案,我想“删除”片段,但片段之前被错误地创建。我不知道为什么,可能是因为稍后完成了“提交”,当需要删除它时,还没有添加片段。因此 getActivity() 返回 null。

解决方案:1)我必须在创建新片段之前检查我是否正确地尝试找到片段的第一个实例 2)我必须将 serRetainInstance(true) 放在该片段上,以便通过方向更改保持它(没有回栈需要因此没问题) 3)而不是在“删除它”之前“重新创建或获取旧片段”,我直接将片段放在活动开始处。在活动开始时实例化它而不是在删除之前“加载”(或实例化)片段变量可以防止 getActivity 问题。

于 2017-03-03T15:20:05.743 回答
0

在 Kotlin 中,您可以尝试这种方式来处理 getActivity() null 条件。

   activity?.let { // activity == getActivity() in java

        //your code here

   }

它将检查活动是否为空,如果不为空,则执行内部代码。

于 2020-06-23T16:55:01.137 回答