在开发者控制台错误报告中,有时我会看到有NPE问题的报告。我不明白我的代码有什么问题。在模拟器上,我的设备应用程序在没有forcecloses的情况下运行良好,但是当调用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) {}
});
}
AsyncTask类
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();
...
}
}
当应用程序从后台恢复时,可能会发生此错误。在这种情况下,我应该如何妥善处理这种情况?
答案 0 :(得分:120)
我似乎找到了解决问题的方法。 给出了非常好的解释here和here。 这是我的例子:
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();
}
}
如果我们打开片段,推送任务,然后快速按回以返回上一个活动,当任务完成时,它将尝试通过调用getActivity()方法访问onPostExecute()中的活动。如果活动已经分离,并且此检查不存在:
if (isAdded())
然后应用程序崩溃。
答案 1 :(得分: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;
}
}
}
正如你所看到的,我已经添加了一个监听器,所以每当我需要Fragments
Activity
而不是标准getActivity()
时,我都需要调用
getAvailableActivity(new IActivityEnabledListener() {
@Override
public void onActivityEnabled(FragmentActivity activity) {
// Do manipulations with your activity
}
});
答案 2 :(得分:17)
最好摆脱这种情况是在调用onAttach
时保持活动参考,并在需要的地方使用活动参考,例如。
@Override
public void onAttach(Context context) {
super.onAttach(context);
mContext = context;
}
@Override
public void onDetach() {
super.onDetach();
mContext = null;
}
已编辑,因为onAttach(Activity)
已弃用&amp;现在正在使用onAttach(Context)
答案 3 :(得分:9)
不要在Fragment中调用需要getActivity()的方法,直到父Activity中的onStart为止。
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();
}
答案 4 :(得分:4)
我已经battling this kind of problem了一段时间,我想我已经提出了一个可靠的解决方案。
我很难确定this.getActivity()
是否会null
返回Fragment
,尤其是如果你正在处理任何类型的网络行为,使您的代码有足够的时间撤回Activity
引用。
在下面的解决方案中,我声明了一个名为ActivityBuffer
的小型管理类。从本质上讲,此class
涉及维护对拥有Activity
的可靠引用,并承诺在有效的Runnable
上下文中执行Activity
可用。如果Runnable
可用,则计划在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;
}
}
最后,在您Fragment
内BaseFragment
延伸getActivity()
的任何区域,如果您对this.getActivityBuffer().safely(...)
的来电不可信,只需拨打ActivityBuffer.IRunnable
和为任务声明void run(final Activity pActivity)
!
然后保证ActivityBuffer
的内容沿着UI线程执行。
然后可以按如下方式使用this.getActivityBuffer().safely(
new ActivityBuffer.IRunnable() {
@Override public final void run(final Activity pActivity) {
// Do something with guaranteed Context.
}
}
);
:
console.log
答案 5 :(得分:3)
The Absolute value of -5 is 5
答案 6 :(得分:1)
我知道这是一个老问题,但我认为我必须提供我的答案,因为我的问题没有被别人解决。
首先:我使用fragmentTransactions动态添加片段。 第二:使用AsyncTasks(服务器上的DB查询)修改我的片段。 第三:我的片段没有在活动开始时实例化 第四:我使用了自定义片段实例化&#34;创建或加载它&#34;为了获得片段变量。 第四:由于方向改变而重建了活动
问题是我想&#34;删除&#34;由于查询答案,片段,但片段之前错误地创建。我不知道为什么,可能是因为&#34;提交&#34;稍后完成,当删除它时,片段尚未添加。因此getActivity()返回null。
解决方案: 1)在创建新片段之前,我必须检查我是否正确地尝试找到片段的第一个实例 2)我必须在该片段上放置serRetainInstance(true)以便通过方向更改(不需要任何后端堆栈因此没有问题) 3)而不是重建或获取旧片段&#34;就在&#34;删除它之前,我直接将片段放在活动开始处。 在活动开始时实例化它而不是&#34; loading&#34; (或实例化)片段变量,然后删除它会阻止getActivity问题。
答案 7 :(得分:0)
在Kotlin中,您可以尝试这种方法来处理getActivity()空条件。
activity.let { // activity == getActivity() in java
//your code here
}
它将检查活动是否为空,如果不为空,则执行内部代码。