我创建了一个ViewPager,其中包含4个带有不同内容的片段。每个片段的底部都有一个按钮栏。当我单击按钮之一时,应更新当前片段的数据。因此,我在活动中实现了一些回调方法。但不幸的是,每次我调用方法reloadArticleListFragment()时,例如当我单击按钮栏中的按钮之一时,出现NullPointerException。我想当前的片段没有附加到活动中,但是我不知道为什么。你有什么建议吗?

谢谢你的帮助!

MainActivity.java

public class MainActivity extends FragmentActivity implements ActionBar.TabListener, DataFragment.Callbacks {

...

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

    // setup ui and instantiate some variables (missing in the example)

    mDataFragment = (AbstractDataFragment) mPagerAdapter.getItem(mViewPager.getCurrentItem());
    mAdapter = mDataFragment.getAdapter();
    rssService.execute(RssService.BLOG_URL);

    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    sharedPreferences.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            if (key.equalsIgnoreCase("feedScope")) {
                mPagerAdapter.setFeedScope(Integer.parseInt(sharedPreferences.getString(key, "0")));
                reloadArticleListFragment();
            } else if (key.equalsIgnoreCase("countySelection")) {
                reloadArticleListFragment();
            }
        }
    });
}

private void setupUI() {
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mActionBar = getActionBar();
    mPagerAdapter = new TabsPagerAdapter(getFragmentManager(), rssService);

    mViewPager.setAdapter(mPagerAdapter);
    mActionBar.setHomeButtonEnabled(false);
    mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // Adding Tabs
    ...

    mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            mActionBar.setSelectedNavigationItem(position);
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

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

@Override
protected void onResume() {
    super.onResume();
    reloadArticleListFragment();
}

@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
    mViewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {

}

@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {

}

private void reloadArticleListFragment() {
    mPagerAdapter.setFilterType(filterType);
    if (mDataFragment != null) {
        mDataFragment.setFilterType(filterType);
        mDataFragment.refreshData(false);
    }
}
...
}


AbstractDataFragment.java

public abstract class AbstractDataFragment extends Fragment implements DataFragment {

...

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    if (!(activity instanceof Callbacks)) {
        throw new IllegalStateException("Activity must implement fragment's callbacks.");
    }
    callbacks = (Callbacks) activity;
}

@Override
public void onDetach() {
    super.onDetach();
    callbacks = sDummyCallbacks;
}

@Override
public void refreshData(boolean force) {
    if (force) {
        if (rssService != null) {
            rssService = new RssService(getActivity());
        }
        rssService.execute(BLOG_URL);
    } else {
        setFilterType(filterType);
    }
    adapter.notifyDataSetChanged(); // NullPointerException is thrown here
}
}


ArticleListFragment.java

public class ArticleListFragment extends AbstractDataFragment {
private ListView listView;

public static ArticleListFragment newInstance(SelectionType selectionType, FilterType filterType, int feedScope) {
    ArticleListFragment fragment = new ArticleListFragment();
    Bundle args = new Bundle();
    args.putSerializable(ARG_SELECTION_TYPE, selectionType);
    args.putSerializable(ARG_FILTER_TYPE, filterType);
    args.putInt(ARG_FEED_SCOPE, feedScope);
    fragment.setArguments(args);
    return fragment;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.article_list, container, false);
    this.listView = (ListView) view.findViewById(R.id.listView);
    this.listView.setEmptyView(view.findViewById(R.id.emptyView));
    return view;
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    if (savedInstanceState != null) {
        if (savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
            setActivatedPosition(savedInstanceState.getInt(STATE_ACTIVATED_POSITION));
        }
    }
    // init image loader if it is not initialized before
    if (!ImageLoader.getInstance().isInited()) {
        initImageLoader();
    }
    initializeAdapter();
    // set click listener
    if (getDataView() != null) {
        getDataView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                getCallbacks().onItemSelected(String.valueOf(position));
            }
        });
    }
}
...
}


//编辑:这是stacktrace

09-05 13:20:03.035    1237-1237/de.ssncomputer.retternews E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: de.ssncomputer.retternews, PID: 1237
    java.lang.RuntimeException: Unable to resume activity {de.ssncomputer.retternews/de.ssncomputer.retternews.views.activities.MainActivity}: java.lang.NullPointerException
        at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2788)
        at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2817)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)
        at android.app.ActivityThread.access$800(ActivityThread.java:135)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5017)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
        at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
        at de.ssncomputer.retternews.views.fragments.AbstractDataFragment.refreshData(AbstractDataFragment.java:202)
        at de.ssncomputer.retternews.views.activities.MainActivity.reloadArticleListFragment(MainActivity.java:186)
        at de.ssncomputer.retternews.views.activities.MainActivity.onResume(MainActivity.java:116)

最佳答案

如果(rssService!= null){
rssService =新的RssService(getActivity());
}


我想你想给


如果(rssService == null){
rssService =新的RssService(getActivity());
}

关于java - 从其 Activity 调用 fragment 的适配器时发生NullPointerException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25684285/

10-11 00:01